ImageView和UIButton

iza*_*zan 3 cocoa-touch objective-c ios

我想创建一个带有自定义图像(背景图像)的按钮,我已经这样做了.如何将imageview分配给may按钮?

谢谢你的回答

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
           action:@selector(goToGeoloc)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0);
UIImage *image = [UIImage imageNamed:@"ico_plan.png"];
UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
Run Code Online (Sandbox Code Playgroud)

tam*_*gal 7

你想要的是:

[button setBackgroundImage:image forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

要么

[button setImage:image forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

  • 这是2015年... Google和StackOverflow正在取代文档. (2认同)

Rob*_*bin 6

@izan你不需要单独UIImageView展示就可以了UIButton.

A 里面UIButton有2个UIImageView.你可以设置这两个imageViews的图像.

您可以使用setImage:forState:方法为第一个imageview设置图像.通过这样做,您无法显示该按钮的任何标题.如果要在按钮上显示标题和图像,则应使用setBackgroundImage:forState:方法.


Thy*_*hys 5

使用setImage方法;

- (void)setImage:(UIImage *)image forState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

所以你的代码就是;

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(goToGeoloc) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0);

UIImage *image = [UIImage imageNamed:@"ico_plan.png"];
[button setImage:image forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

或者我仍然希望你的文字显示出来;

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

哪会导致;

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(goToGeoloc) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0);

UIImage *image = [UIImage imageNamed:@"ico_plan.png"];
[button setBackgroundImage:image forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

UIButton文档; http://bit.ly/kruq5y