首页 > 解决方案 > `UIbutton.setImage` 和更改 `UIbutton.imageView` 有什么区别?

问题描述

UIbutton.setImage和 改变 和有什么不一样UIbutton.imageView

buttonA.imageView?.image = UIImage(named: "name")

buttonA.setImage(UIImage(named: "name"), for: .normal)

当我尝试使用setImage然后尝试使用 获取它的位置frame.origin.x时,返回的位置不是我所期望的,所以我使用了.imageView?.image方法。但是当我使用它时,我观察到单击按钮会在短时间内更改图像,然后再继续。

标签: iosswiftxcode

解决方案


For some clarification...

If you set the .image property directly:

buttonA.imageView?.image = UIImage(named: "name")

You have not informed the button class that it has a new image property.

The same thing applies to setting the title:

buttonA.titleLabel?.text = "My Title"

That will change the text of the title label, but only until the next UI update... at which point UIKit will use the value assigned via:

buttonA.setTitle("Button A", for: .normal)

That's why it's important to use both .setImage(...) and .setTitle(...) instead of setting the property itself.


推荐阅读