1. 程式人生 > >今日分享-自定義返回按鈕(與系統按鈕位置一致)

今日分享-自定義返回按鈕(與系統按鈕位置一致)

首先來看三張圖:

程式碼已貼出在圖片下方

系統自帶返回按鈕(顯示文字內容)

系統自帶返回按鈕(隱藏文字)

自定義返回按鈕

無文字返回按鈕設定:

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

swift

UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -60), for: UIBarMetrics.default
)

自定義返回按鈕(位置與系統位置一致) 為UIViewController新增extension方法,方便呼叫

extension UIViewController{
    // xzCustomBackBarButtonItem
    func customBackBarButtonItem(target:AnyObject?,action:Selector?){

        var action1 = action
        if action1 == nil {
           action1 = #selector(self.navigationController?.popViewController(animated:))
} var target1 = target if target1 == nil { target1 = self.navigationController } let backBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "new-sys-jiantou"), style: UIBarButtonItemStyle.plain, target: target1, action: action1) //UIImage.init(named: "new-sys-jiantou") UI提供返回圖片
let fixBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) fixBarButtonItem.width = -10 self.navigationItem.leftBarButtonItems = [fixBarButtonItem,backBarButtonItem] } }