UIView 擴充套件的大小和框架屬性

如果我們想獲得檢視原點的 x-cordinate,那麼我們需要編寫如下:

view.frame.origin.x

對於寬度,我們需要寫:

view.frame.size.width

但是如果我們為 UIView 新增一個簡單的擴充套件,我們可以非常簡單地獲得所有屬性,例如:

view.x
view.y
view.width
view.height

它還有助於設定這些屬性,如:

view.x = 10
view.y = 10
view.width = 100
view.height = 200

簡單的擴充套件將是:

extension UIView {
    
    var x: CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            self.frame = CGRect(x: newValue, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height)
        }
    }
    
    var y: CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame = CGRect(x: self.frame.origin.x, y: newValue, width: self.frame.size.width, height: self.frame.size.height)
        }
    }
    
    var width: CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: newValue, height: self.frame.size.height)
        }
    }
    
    var height: CGFloat {
        get {
            return self.frame.height
        }
        set {
            self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: newValue)
        }
    }
}

我們需要在專案中新增這個類檔案,它可以在整個專案中使用!