美文网首页
便利构造器

便利构造器

作者: Rayla_周周 | 来源:发表于2017-07-31 17:19 被阅读0次

    类方法

    extension UIBarButtonItem {
         class func createItem(imageName:String,highImageName : String,size : CGSize) -> UIBarButtonItem {
         let btn = UIButton()
         btn.setImage(UIImage.init(named: imageName), for: .normal)
         btn.setImage(UIImage.init(named: highImageName), for: .highlighted)
         btn.frame = CGRect(origin: CGPoint(), size: size)
         return UIBarButtonItem(customView: btn);
         }
    
    • 调用方式
     let size = CGSize(width: 40, height: 40)
     let historyItem = UIBarButtonItem.createItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
    

    构造方法

    • 便利构造函数(推荐使用)
      1. convenience开头
      2. 在构造函数中必须明确调用一个设计的构造函数(self调用)
     convenience init(imageName:String,highImageName : String = "",size : CGSize) {
            let btn = UIButton()
            btn.setImage(UIImage.init(named: imageName), for: .normal)
            if highImageName != "" {
                /// 设置默认值
                btn.setImage(UIImage.init(named: highImageName), for: .highlighted)
            }
            btn.frame = CGRect(origin: CGPoint(), size: size)
            self.init(customView:btn)
        }
    
    • 调用方式
     let size = CGSize(width: 40, height: 40)
     let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
    

    相关文章

      网友评论

          本文标题:便利构造器

          本文链接:https://www.haomeiwen.com/subject/ucyrlxtx.html