在日常代码中,我们常常要重复用到view的一些属性,比如view.center.x、view.frame.origin.y等等,每次用到都要写一遍view.center.x之类会让代码看起来很麻烦,所以必要用extension来扩展一些属性。
贴代码:
import UIKit
/// MARK - UIView
extension UIView {
// MARK: - 常用位置属性
public var left:CGFloat {
get {
return self.frame.origin.x
}
set(newLeft) {
var frame = self.frame
frame.origin.x = newLeft
self.frame = frame
}
}
public var top:CGFloat {
get {
return self.frame.origin.y
}
set(newTop) {
var frame = self.frame
frame.origin.y = newTop
self.frame = frame
}
}
public var width:CGFloat {
get {
return self.frame.size.width
}
set(newWidth) {
var frame = self.frame
frame.size.width = newWidth
self.frame = frame
}
}
public var height:CGFloat {
get {
return self.frame.size.height
}
set(newHeight) {
var frame = self.frame
frame.size.height = newHeight
self.frame = frame
}
}
public var right:CGFloat {
get {
return self.left + self.width
}
}
public var bottom:CGFloat {
get {
return self.top + self.height
}
}
public var centerX:CGFloat {
get {
return self.center.x
}
set(newCenterX) {
var center = self.center
center.x = newCenterX
self.center = center
}
}
public var centerY:CGFloat {
get {
return self.center.y
}
set(newCenterY) {
var center = self.center
center.y = newCenterY
self.center = center
}
}
}
当你需要使用一个视图的y轴顶点坐标的时候,只需要view.top即可。
其他类型的extension也是如此,通过这种方法,会让我们的代码更加简洁。