ios - UIbutton 的图像没有改变
问题描述
我做了一个面包屑导航,它显示了您选择的每个单元格的标题。对于第一个屏幕 - 在选择单元格之前,我想显示一个主页图标。选择一个单元格后,我想更改图标。
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
breadcrumbsTitles.count <= 1 ? button.setImage(UIImage(named: "home_1x"), for: .normal) : button.setImage(UIImage(named: "arrow_left"), for: .normal)
button.addTarget(self, action: #selector(backPressed), for: .touchUpInside)
//container for the bread crumb navigation
container.addSubview(button)
breadcrumbsTitles包含我容器中的所有单元格/视图:
public var breadcrumbsTitles: [String] {
return self.viewControllers.map {
$0.title ?? ""
}
}
breadcrumbsTitles.count
返回面包屑导航中的标题数。为什么选择一个单元格时我的按钮不改变其图像?我也尝试使用if-else语句,但它也不起作用:
if breadcrumbsTitles.count <= 1{
button.setImage(UIImage(named: "home_1x"), for: .normal)
} else ... // set image to "arrow_left"
为什么在我选择单元格或其他内容后我的按钮图像没有改变?
解决方案
您的容器尚未准备好添加更多 addSubview 视图,您可以先更正容器视图然后正常工作。
- 我添加了 viewDidLoad 工作正常
导入 UIKit
class ViewController: UIViewController {
let breadcrumbsTitles = ["1","2","3"]
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
breadcrumbsTitles.count <= 1 ? button.setImage(UIImage(named: "default"), for: .normal) : button.setImage(UIImage(named: "arrow_left"), for: .normal)
button.addTarget(self, action: #selector(btnPress), for: .touchUpInside)
button.backgroundColor = UIColor.red
self.view.addSubview(button)
}
@objc func btnPress() {
}
}