在oc中为了增强已有类的功能,我们经常使用分类。使用分类,我们可以在不破坏原有类的结构的前提下,对原有类进行模块化的扩展。
但是在swift中没有分类这种写法了。相对应的是swift中只有扩展(Extensions)。
下面是swift中扩展(Extensions)的说明
扩展就是向一个已有的类、结构体、枚举类型或者协议类型添加新功能(functionality)。这包括在没有权限获取原始源代码的情况下扩展类型的能力(即逆向建模)。扩展和 Objective-C 中的分类(categories)类似。(不过与 Objective-C 不同的是,Swift 的扩展没有名字。)
下面是swift实现对UIView的分类:
extension UIView {
//x
var x:CGFloat {
set{
var oldFrame = self.frame
oldFrame.origin.x = newValue;
self.frame = oldFrame
}
get{
return self.frame.origin.x
}
}
//y
var y:CGFloat {
set{
var oldFrame = self.frame
oldFrame.origin.y = newValue;
self.frame = oldFrame
}
get{
return self.frame.origin.y
}
}
//height
var height:CGFloat {
set{
var oldFrame = self.frame
oldFrame.size.height = newValue;
self.frame = oldFrame
}
get{
return self.frame.size.height
}
}
//width
var width:CGFloat {
set{
var oldFrame = self.frame
oldFrame.size.width = newValue;
self.frame = oldFrame
}
get{
return self.frame.size.width
}
}
//top
var top:CGFloat {
set{
var oldFrame = self.frame
oldFrame.origin.y = newValue;
self.frame = oldFrame
}
get{
return self.frame.origin.y
}
}
//left
var left:CGFloat {
set{
var oldFrame = self.frame
oldFrame.origin.x = newValue;
self.frame = oldFrame
}
get{
return self.frame.origin.x
}
}
//bottom
var bottom:CGFloat {
set{
var oldFrame = self.frame
oldFrame.origin.y = newValue - oldFrame.size.height;
self.frame = oldFrame
}
get{
return self.frame.origin.y + self.frame.size.height
}
}
//right
var right:CGFloat {
set{
var oldFrame = self.frame
oldFrame.origin.x = newValue+oldFrame.size.width;
self.frame = oldFrame
}
get{
return self.frame.origin.x + self.frame.size.width
}
}
//size
var size:CGSize {
set{
var oldFrame = self.frame
oldFrame.size = newValue
self.frame = oldFrame
}
get{
return self.frame.size
}
}
//origin
var origin: CGPoint{
set{
var oldFrame = self.frame
oldFrame.origin = newValue;
self.frame = oldFrame
}
get{
return self.frame.origin
}
}
}
|
请发表评论