Swift - UIView + Extension

2017-07-17  本文已影响0人  Soullamet

在OC中我们通过类目Category做UIView属性宽展,方便我们获取常用属性,(x、y、宽、高等)
在Swift中我们也一样可以通过extension来宽展属性
直接上代码,很容易明白

extension UIView{
    
    var x:CGFloat{
        get{
            return self.frame.origin.x
        }
        set(newVal){
            var temF :CGRect = frame
            temF.origin.x = newVal
            frame = temF
        }
    }
    
    var y:CGFloat{
        get{
            return self.frame.origin.y
        }
        set(newVal){
            var temF :CGRect = frame
            temF.origin.y = newVal
            frame = temF
        }
    }
    
    var size:CGSize{
        get{
            return self.frame.size
        }
        set(newVal){
            var temF :CGRect = frame
            temF.size = newVal
            frame = temF
        }
    }
    
    var width:CGFloat{
        get{
            return self.bounds.width
        }
        set(newVal){
            var temF :CGRect = frame
            temF.size.width = newVal
            frame = temF
        }
    }
    
    var height:CGFloat{
        get{
            return self.bounds.height
        }
        set(newVal){
            var temF :CGRect = frame
            temF.size.height = newVal
            frame = temF
        }
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读