2017-10-12 76 views
1

我一直在試圖構建一個自定義的UINavigationBar,但我的button.frame輸入沒有任何效果。Swift 4 - 無法控制UIButton大小添加到UINavigationBar

override func viewDidLoad() { 
    super.viewDidLoad() 

    let button = UIButton(type: .custom) 
    button.setImage(UIImage(named: "I_sent"), for: .normal) 
    button.addTarget(self, action: #selector(action), for: .touchUpInside) 

    // This doesn't seem to have an effect: 
    button.frame = CGRect(x: 0, y: 0, width: 30, height: 30) 
    button.contentMode = .scaleAspectFit 

    let item = UIBarButtonItem(customView: button) 
    navigationItem.rightBarButtonItem = item 
} 

@objc func action() { 
    print("Action") 
} 

運行時代碼(以上)出現這樣的:

但我想使它看起來像這樣:

任何幫助非常感謝!

回答

0

添加約束到UIButton爲:

button.widthAnchor.constraint(equalToConstant: button.frame.size.width).isActive = true 
button.heightAnchor.constraint(equalToConstant: button.frame.size.height).isActive = true 

希望它能幫助!

+0

它的工作!非常感謝! – Jake

+0

@Jake快樂編碼:-) –