swift 基礎小結02 -- VFL約束、屬性的get和set方法、懶加載、方法替換

1、屬性的get和set方法
    
    一、自定義屬性的set和get方法
    
    private(set) var _image:UIImage?
    //自定義屬性get,set
    var image : UIImage?{
        get{
            return _image
        }
        set(newValue){
            _image = newValue
            self.imageView?.image = _image
        }
    }
    二、重寫父類屬性的set和get方法
 
//重寫父類屬性get,set
    override var tag:Int{
       
        get{
           return super.tag
        }
        set(newValue){
            super.tag = newValue
            self.button?.tag = newValue
        }
    
 
 
2、VFL添加約束
 
    和objective-c中類似,代碼以下
let tabbarHeight:CGFloat = 49.0
func setupBaseUI(){
        self.contentView.translatesAutoresizingMaskIntoConstraints = false
        self.lineView.translatesAutoresizingMaskIntoConstraints = false
        self.tabBar.translatesAutoresizingMaskIntoConstraints = false
        let views = self.ConstraintDictionWithArray(nameArray: [self.contentView,self.lineView,self.tabBar,self.view], object: self);
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[contentView]|", options: NSLayoutFormatOptions.alignAllLeft, metrics: nil, views: views))
       
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[tabBar]|", options: NSLayoutFormatOptions.alignAllLeft, metrics: nil, views: views))
      
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[contentView][tabBar(tabbarHeight)]|", options: NSLayoutFormatOptions.alignAllLeft, metrics: ["tabbarHeight":(self.isIphoneX() ? tabbarHeight_iphoneX : tabbarHeight)], views: views))
      
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[lineView]|", options: NSLayoutFormatOptions.alignAllLeft, metrics: nil, views: views))
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[lineView(0.5)]", options: NSLayoutFormatOptions.alignAllLeft, metrics: nil, views: views))
    }
 
//MARK: 至關於OC中的NSBinding(由於oc中沒有宏定義,沒有NSBinding這個宏定義,因此寫一個方法代替這個方法)
    func ConstraintDictionWithArray(nameArray:Array<UIView>,object:AnyObject) -> Dictionary<String,AnyObject> {
       
        var dict:Dictionary<String,AnyObject> = [:]
       
        var count:UInt32 = 0
       
        let ivars = class_copyIvarList(object.classForCoder, &count)
       
        for i in 0...Int(count) {
           
            let obj = object_getIvar(object, ivars![i])
           
            if let temp = obj as? UIView {
               
                if nameArray.contains(temp){
                   
                    let name = String.init(cString: ivar_getName(ivars![i])!)
                   
                    dict[name] = temp
                }
               
            }
        }
        free(ivars)
       
        return dict
    }
 
3、懶加載
    
    一、懶加載建立label
    
//MARK: 懶加載建立label
    lazy var lazyLabel: UILabel = self.addLabel_d(title: "");
    func addLabel_d(title:String) -> UILabel {
        let label = UILabel(frame: CGRect.init(x: 0, y: 0, width: 200, height: 40))
        label.center = self.view.center
        label.backgroundColor = UIColor.gray
        label.textColor = UIColor.white
        label.textAlignment = NSTextAlignment.center
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.text = title
        label.font = UIFont.systemFont(ofSize: 17)
        return label;
    }
    
    二、懶加載數組
//lazy
    lazy var datasource:NSArray = {
       
        var tmpdatasource = NSArray(objects: ["title":"dispatch使用","content":["sync -- 同步","async -- 異步","delay -- 延遲執行三秒","main -- 主線程","global -- 全局併發隊列"]],["title":"網絡請求","content":["GET -- 請求","POST -- 請求","下載圖片"]],["title":"自定義組件","content":["toast","。。。"]])
       
        return tmpdatasource
    }()
 
4、方法替換
 
extension UIViewController{
   
    public class func initializeMethod() {
        let originalSelector = #selector(UIViewController.viewWillAppear(_:))
        let swizzledSelector = #selector(UIViewController.dealWithJF_Tabbar(animated:))
        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
        //在進行 Swizzling 的時候,須要用 class_addMethod 先進行判斷一下原有類中是否有要替換方法的實現
        let didAddMethod: Bool = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
        //若是 class_addMethod 返回 yes,說明當前類中沒有要替換方法的實現,因此須要在父類中查找,這時候就用到 method_getImplemetation 去獲取 class_getInstanceMethod 裏面的方法實現,而後再進行 class_replaceMethod 來實現 Swizzing
        if didAddMethod {
            class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
           
        } else {
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
           
        }
       
    }
    @objc func dealWithJF_Tabbar(animated: Bool) {
      
        self.dealWithJF_Tabbar(animated: animated)
         print("處理自定義tabbar隱藏問題")
        self.jf_tabBarController?.tabBar.isHidden = self.jf_hidesBottomBarWhenPushed;
    }
}
 
而後在appdelegate中使用下面方法:
 
    UIViewController.initializeMethod()
相關文章
相關標籤/搜索