问题描述
我对这件事失去了理智.我将UIButton连接为插座.我想改变它的形象.在viewDidLoad函数中,我尝试像这样设置图像:
I'm losing my mind over this one. I have UIButton connected as Outlet. I want to change it's image. In the viewDidLoad function, I try to set the image like so:
[button1 setImage:[UIImage imageNamed:@"house.png"] forState:UIControlStateNormal];
什么都没发生.但是,如果我使用ImagePicker,它将以某种方式起作用.在ImagePickers函数"didFinishPickingImage"中,我重复上述与设置图像完全相同的命令,该命令可以正常显示图像.
Nothing happens. However, if I use ImagePicker, it somehow works. In the ImagePickers function "didFinishPickingImage", I repeat the exactly same command as above for setting image and it works, the image is displayed normally.
我一直在想按钮的图像本身不会刷新,而是试图调用[button1 setNeedsDisplay]或[button1.imageView setNeedsDisplay]甚至[button1.imageView.image setNeedsDisplay]都不起作用.
I've been thinking that maybe the button's image is not refreshing itself, but trying to call [button1 setNeedsDisplay], or [button1.imageView setNeedsDisplay] or even [button1.imageView.image setNeedsDisplay] does nothing.
有人对此有任何想法吗?我现在已经浪费了两个小时,我真的很沮丧,因为我敢肯定原因一定很愚蠢,难以置信.
Does anyone have any idea about this? I've wasted two hours by now and I'm really getting frustrated, because I'm certain that the reason must be so stupid it's unbelivable.
推荐答案
适用于任何会遇到类似情况的人;我在表单元格的自定义单元格中使用提到的按钮.但是,不是立即加载单元格(即在viewDidLoad/viewWillAppear等内部),而是在tableView:cellForRowAtIndexPath函数内部.那时我所有的按钮变量都为零.我的解决方案是在创建单元后加载图像,此后它立即可以正常工作.
For anyone who will find themselves in a similar situation; I was using the mentioned button inside a custom cell for table view. However, the cells aren't loaded right away (i.e. inside viewDidLoad/viewWillAppear etc.), but inside the tableView:cellForRowAtIndexPath function. All my button variables were nil at that point. My solution was to load the image after the cell has been created and it has worked straight away afterwards.
这篇关于UIButton setImage不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!