3 UIBarButtonItem+Extension

//UIBarButtonItem+Extension

import UIKit

extension UIBarButtonItem {

//分类里不能设置指定构造函数:      init(title:String) { }

    //便利构造函数可以返回nil对象  convenience init?    imageName定义为默认值是nil
    convenience init?(title: String,imageName: String? = nil,target:Any?,action:Selector) {
        //self 调用init构造函数
        self.init()
        
        let button = UIButton()
        
        button.addTarget(target, action: action, for: .touchUpInside)
        button.setTitle(title, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .normal)
        button.setTitleColor(UIColor.orange, for: .highlighted)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.sizeToFit()
        
        if imageName != nil {
            button.setImage(UIImage(named:imageName!), for: .normal)
        }
        
        self.customView = button
        
    }
    
    
}
 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", target: self, action:#selector(registerButtonAction))
 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", target: self, action:#selector(loginButtonAction))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容