如何以编程方式更改UIButton内的UIImageView的图像?

我用UIImageView和UILabel创build了一个UIButton,通过Tim的这个问题和答案的帮助,现在我想改变button点击事件的UIImageView的图像。 我试过[sender.imageView setImage:image]但它不工作

您可以:

1 – 保留在你的viewController的UIButton内的UIImageView的引用

2 – inheritanceUIButton并自己添加UIImageView。

3 – 添加UIImageView时,添加一个标签(view.tag),并从发件人获取视图时,您可以

 UIView *view = (UIView *)sender; UIImageView *imageView = [view viewWithTag:123]; //do what you must with the imageView. 

标签可以是任何数字。

编辑

这是你应该如何在UIImageView上设置标签,而不是在UIButton上。 我从Tim的回答中复制了这个代码:

 // Create the button UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // Now load the image and create the image view UIImage *image = [UIImage imageNamed:@"yourImage.png"]; UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(/*frame*/)]; [imageView setImage:image]; // Create the label and set its text UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(/*frame*/)]; [label setText:@"Your title"]; // Set a tag on the UIImageView so you can get it later imageView.tag = 123; // Put it all together [button addSubview:label]; [button addSubview:imageView];