【问题标题】:How to change image of UIImageView that is inside a UIButton programmatically?如何以编程方式更改 UIButton 内的 UIImageView 的图像?
【发布时间】:2015-08-15 04:08:59
【问题描述】:

在 Tim 的 this 问答的帮助下,我创建了一个带有 UIImageView 和 UILabel 的 UIButton,现在我想在按钮单击事件上更改 UIImageView 的图像。 我试过[sender.imageView setImage:image] 但它不起作用

【问题讨论】:

    标签: ios objective-c iphone uiimageview uibutton


    【解决方案1】:

    你可以:

    1 - 在 vi​​ewController 的 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 上。我从 here 的 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];
    

    【讨论】:

    • 不,我不想更改按钮的图像,而是该按钮内的 UIImageView,你读过这个stackoverflow.com/questions/1116114/… 问题和蒂姆的回答了吗??
    • 这里的123是之前设置的同一个标签还是新的?
    • 它必须与您之前设置的标签相同。我以“123”为例。如果之前设置了700,这里就需要使用700,比如
    • 应用程序在UIImageView *imageView = [button viewWithTag:123];不兼容的指针 UIImageView 与 UIView 类型崩溃
    • 你在设置视图时是否使用123作为标签?该错误意味着正在获取的视图不是 UIImageView
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2017-03-23
    • 2015-10-15
    相关资源
    最近更新 更多