swift4.2 导航栏系统方法添加图标及跳转

这是使用系统的方法

        var img = UIImage(named: "max")
        let item = UIBarButtonItem(image: img, style: UIBarButtonItemStyle.Plain, target: self, action: nil)
        self.navigationItem.rightBarButtonItem = item 

下面是使用自定义的方法

import UIKit
 
class ViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //搜索按钮
        let button1 = UIButton(frame:CGRect(x:0, y:0, width:18, height:18))
        button1.setImage(UIImage(named: "search"), for: .normal)
        button1.addTarget(self,action:#selector(tapped1),for:.touchUpInside)
        let barButton1 = UIBarButtonItem(customView: button1)
         
        //设置按钮
        let button2 = UIButton(frame:CGRect(x:0, y:0, width:18, height:18))
        button2.setImage(UIImage(named: "settings"), for: .normal)
        button2.addTarget(self,action:#selector(tapped2),for:.touchUpInside)
        let barButton2 = UIBarButtonItem(customView: button2)
         
        //按钮间的空隙
        let gap = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil,
                                  action: nil)
        gap.width = 15
         
        //用于消除右边边空隙,要不然按钮顶不到最边上
        let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil,
                                     action: nil)
        spacer.width = -10
         
        //设置按钮(注意顺序)
        self.navigationItem.rightBarButtonItems = [spacer,barButton2,gap,barButton1]
    }
     
    func tapped1(){
        print("搜索按钮点击")
    }
     
    func tapped2(){
        print("设置按钮点击")
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容