簡體   English   中英

UIbutton 的圖像沒有改變

[英]UIbutton 's image not changing

我做了一個面包屑導航,顯示您選擇的每個單元格的標題。 對於第一個屏幕 - 在選擇單元格之前,我想顯示一個主頁圖標 選擇一個單元格后,我想更改圖標。

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)

面包屑標題包含我的容器中的所有單元格/視圖:

public var breadcrumbsTitles: [String] {
        return self.viewControllers.map {
            $0.title ?? ""
        }
    }

breadcrumbsTitles.count

返回面包屑導航中的標題數。 Why is my button not changing its image when one cell is selected? 我也嘗試使用if-else語句,但它也不起作用:

if breadcrumbsTitles.count <= 1{
button.setImage(UIImage(named: "home_1x"), for: .normal)
} else ... // set image to "arrow_left"

為什么在我選擇一個單元格或其他東西后我的按鈕圖像沒有改變?

您的容器尚未准備好添加更多 addSubview 視圖,您可以先更正容器視圖,然后才能正常工作。

  1. 我在 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() {


    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM