用習(xí)慣了OC的工具類UIView+Additions,之前寫代碼的時(shí)候一般直接寫view.top或者view.height現(xiàn)在沒有了就得寫成view.frame.origin.y或者view.frame.size.height這..真的讓人很奔潰..
本來想找個swift版本的,但是沒有找到,所以決定自己寫一個.
首先要創(chuàng)建個UIView+Additions類...我以為創(chuàng)建Swift File像Objective-C File文件一樣也是可以選擇擴(kuò)展類的,會自動生成中間的+號,事實(shí)證明我想多了..這個+加應(yīng)該是只能自己打上去了..
就是選這個,點(diǎn)完之后不要懷疑人生,取個名字創(chuàng)建就可以了
創(chuàng)建完也不要懷疑人生,里面就是很干凈的...
下面就是代碼了,其實(shí)都是非常簡單的set get方法, 但是在開發(fā)的時(shí)候可以節(jié)省很多時(shí)間,而且代碼也不會看著那么的腫脹...
import Foundation
import UIKit
extension UIView {
public var left: CGFloat{
get{
return self.frame.origin.x
}
set{
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
public var top: CGFloat{
get{
return self.frame.origin.y
}
set{
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
public var right: CGFloat{
get{
return self.frame.origin.x + self.frame.size.width;
}
set{
var frame = self.frame
frame.origin.x = newValue - frame.size.width;
self.frame = frame
}
}
public var bottom: CGFloat{
get{
return self.frame.origin.y + self.frame.size.height;
}
set{
var frame = self.frame
frame.origin.y = newValue - frame.size.height;
self.frame = frame
}
}
public var centerX: CGFloat{
get{
return self.center.x;
}
set{
var center = self.center
center.x = newValue
self.center = center
}
}
public var centerY: CGFloat{
get{
return self.center.y;
}
set{
var center = self.center
center.y = newValue
self.center = center
}
}
public var width: CGFloat{
get{
return self.frame.size.width;
}
set{
var frame = self.frame
frame.size.width = newValue;
self.frame = frame
}
}
public var height: CGFloat{
get{
return self.frame.size.height;
}
set{
var frame = self.frame
frame.size.height = newValue;
self.frame = frame
}
}
public var origin: CGPoint{
get{
return self.frame.origin
}
set{
var frame = self.frame
frame.origin = newValue;
self.frame = frame
}
}
public var size: CGSize{
get{
return self.frame.size
}
set{
var frame = self.frame
frame.size = newValue;
self.frame = frame
}
}
func removeAllSubviews(){
while self.subviews.count > 0 {
let subView = self.subviews.first
subView?.removeFromSuperview()
}
}
}
最后,如果你的view是使用SnapKit設(shè)置的約束,那同一個view就盡量都用SnapKit,不然也是容易出錯的,因?yàn)槭褂肧napKit約束后并不能立刻反應(yīng)到frame上,這個問題在oc中使用過Masory應(yīng)該也都知道.