swift UIView+Additions

用习惯了OC的工具类UIView+Additions,之前写代码的时候一般直接写view.top或者view.height现在没有了就得写成view.frame.origin.y或者view.frame.size.height这..真的让人很奔溃..

本来想找个swift版本的,但是没有找到,所以决定自己写一个.

首先要创建个UIView+Additions类...我以为创建Swift File像Objective-C File文件一样也是可以选择扩展类的,会自动生成中间的+号,事实证明我想多了..这个+加应该是只能自己打上去了..

swift UIView+Additions_第1张图片

就是选这个,点完之后不要怀疑人生,取个名字创建就可以了

创建完也不要怀疑人生,里面就是很干净的...

下面就是代码了,其实都是非常简单的set get方法, 但是在开发的时候可以节省很多时间,而且代码也不会看着那么的肿胀...

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设置的约束,那同一个view就尽量都用SnapKit,不然也是容易出错的,因为使用SnapKit约束后并不能立刻反应到frame上,这个问题在oc中使用过Masory应该也都知道.

你可能感兴趣的:(swift UIView+Additions)