点击时 UIButton 图像不会改变 [英] UIButton image doesn't change when tapped

查看:30
本文介绍了点击时 UIButton 图像不会改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击它时,我需要将图像按钮更改为不同的图像.很简单,那里有样本,但它们对我不起作用.这是我按照示例尝试的:

I need to have an image button change to a different image when I tap it. Simple enough, and there are samples out there, but they don't work for me. This is what I tried following the examples:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(20, 270, 200, 40.0);
[button setImage:[UIImage imageNamed:@"butterfly3.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"clicked.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Submit" forState:UIControlStateNormal];
[scrollView button];

现在,我注意到我的按钮设置为在 UIControlEventTouchDown 上执行它的操作,所以我将它添加到点击"控件状态,如下所示:

Now, I notice that my button is set to perform its action on UIControlEventTouchDown so I added it to the "clicked" control states like this:

[button setImage:[UIImage imageNamed:@"clicked.png"] forState:UIControlStateSelected | UIControlStateHighlighted | UIControlEventTouchDown];

但图像仍然保持不变.我错过了什么?

but the image still stays the same. What am I missing?

推荐答案

问题是我的 buttonPressed 方法在主线程上做了一个 long(ish) 查询,由于某种原因,按钮的突出显示在这样的情况下不起作用一个案例.

The issue was that my buttonPressed method did a long(ish) query on the main thread and for some reason the highlighting of the button doesn't work in such a case.

当我将查询移到单独的线程时,突出显示又重新开始.

When I moved the query to a separate thread the highlight went back on.

为了完成起见,我将代码带到这里.最初我通过 Parse.com API 获取对象,如下所示:

For the sake of completion I'll bring the code here. Initially I was fetching objects through Parse.com API like this:

[myQuery findObjects]

上面的代码在主线程上执行查询并阻止其他所有内容.

This above does the query on the main thread and blocks everything else.

然后我将其更改为在这样的单独线程中获取:

Then I changed it to fetching in a separate thread like this:

[myQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if(!error) {
            // whatever is needed to be done
        }
    } else {
        NSLog(@"Error while fetching objects %@", error.description);
    }
}];

这篇关于点击时 UIButton 图像不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆