1.创建一个swift文件
h1 命名可以按照OC的习惯命名,例如UIView+Extension
图例1png
2.分类实现,如下UIView的分类写法书写
import Foundation
import UIKit
extension UIView
{
public var x:CGFloat
{
get{
return self.frame.origin.x
}
set{
var frame = self.frame
frame.origin.x = x
self.frame = frame
}
}
public var y:CGFloat
{
get{
return self.frame.origin.y
}
set{
var frame = self.frame
frame.origin.y = y
self.frame = frame
}
}
public var width:CGFloat
{
get{
return self.frame.size.width
}
set{
var frame = self.frame
frame.size.width = width
self.frame = frame
}
}
public var height:CGFloat
{
get{
return self.frame.size.height
}
set{
var frame = self.frame
frame.size.height = height
self.frame = frame
}
}
public var centerX:CGFloat
{
get{
return self.center.x
}
set{
var center = self.center
center.x = centerX
self.center = center
}
}
public var centerY :CGFloat
{
get{
return self.center.y
}
set{
var center = self.center
center.y = centerY
self.center = center
}
}
public var size:CGSize
{
get{
return self.frame.size
}
set{
var tempFrame = self.frame
tempFrame.size = size
self.frame = tempFrame
}
}
}
网友评论