簡體   English   中英

如何以編程方式更改UIButton內的UIImageView的圖像?

[英]How to change image of UIImageView that is inside a UIButton programmatically?

問題和解答(由Tim回答)的幫助下,我使用UIImageView和UILabel創建了一個UIButton,現在我想在按鈕單擊事件上更改UIImageView的圖像。 我試過了[sender.imageView setImage:image]但它不起作用

您可以:

1-在viewController的UIButton內保留對UIImageView的引用

2-子類化UIButton並自己添加UIImageView。

3-添加UIImageView時,在其中添加一個標簽(view.tag),然后從發送方獲取視圖時,您可以

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

標簽可以是任何數字。

編輯

這就是您應該在UIImageView而不是UIButton上設置標簽的方式。 我從這里的蒂姆的答案中復制了這段代碼:

// 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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM