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)
}
}
}
我们需要在项目中添加这个类文件,它可以在整个项目中使用!