Navigation bar 的注意事項

    

Navigation bar 的注意事項

Bar button item 使用 button 作爲 custom view,初始化 isEnabled 爲 false,注意順序

需要設置 bar button item 的 custom view 爲 button,但一開始 isEnabled 要爲 false。

生成一個 button

let leftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 44))
leftButton.setTitleColor(UIColor.green, for: .normal)
leftButton.setTitleColor(UIColor.red, for: .disabled)
leftButton.setTitle("Enabled", for: .normal)
leftButton.setTitle("Disabled", for: .disabled)
leftButton.addTarget(self, action: #selector(leftButtonClicked(_:)), for: .touchUpInside)

如果先設置 isEnabled,後設置 bar button item

leftButton.isEnabled = falsenavigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)

結果 isEnabled 還是 true

1089786-20170108182932878-197557089.png

正確的順序

navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
leftButton.isEnabled = false // or navigationItem.leftBarButtonItem?.isEnabled = false

結果 isEnabled 是 false

1089786-20170108183001816-1496612822.png

改變 navigation bar isTranslucent 屬性會改變 view 的座標

放置兩個 label。其中, frameLabel 沒有添加約束(NSLayoutConstraint),constraintLabel 左、右、下都有約束,與 view 相接。

1089786-20170108183020456-1532509729.png

設置右上角按鈕動作

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Change", style: .plain, target: self, action: #selector(rightButtonClicked(_:)))

改變 navigation bar isTranslucent 屬性,顯示 label 的座標

@objc private func rightButtonClicked(_ sender: AnyObject) {
        navigationController?.navigationBar.isTranslucent = !navigationController!.navigationBar.isTranslucent
        
        updateLabelContent()
}    
private func updateLabelContent() {
    title = navigationController!.navigationBar.isTranslucent ? "Translecent" : "Opaque"
        
    let frameLabelOrigin = frameLabel.frame.origin
    frameLabel.text = "Frame label. x = \(frameLabelOrigin.x), y = \(frameLabelOrigin.y)"
        
    let constraintLabelOrigin = constraintLabel.frame.origin
    constraintLabel.text = "Constraint label. x = \(constraintLabelOrigin.x), y = \(constraintLabelOrigin.y)"
        
    print("\(title)")    print("Status bar frame:", UIApplication.shared.statusBarFrame) // (0.0, 0.0, 375.0, 20.0)
    print("Navigation bar frame:", navigationController!.navigationBar.frame) // (0.0, 20.0, 375.0, 44.0)}

通過點擊右上角按鈕,來查看變化。

透明時

1089786-20170108185714441-610472055.png

不透明時

1089786-20170108185737253-1907065168.png

View controller 的 view 座標改變,Status bar 和 navigation bar 的座標不變

1089786-20170108183218628-341780181.png

Navigation bar 從不透明變透明,status bar 和 navigation bar 的座標都不變。整個 view 下移64,高度減小64,不會超出 window。沒加約束的 frameLabel 座標不變,但相對 window 的位置隨着 view 一起下移。添加約束的 constraintLabel 的座標改變,但是相對 window 的位置不變。

如果需要改變 navigation bar isTranslucent 屬性,就要考慮對其他 view 會不會有影響,是否使用約束來定位。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章