swift为UIView添加extension扩展frame

时间:2023-08-03 14:22:08

添加swift file:UIView+Extension

import UIKit

extension UIView {

    // x
var x : CGFloat { get { return frame.origin.x
} set(newVal) { var tmpFrame : CGRect = frame
tmpFrame.origin.x = newVal
frame = tmpFrame
}
} // y
var y : CGFloat { get { return frame.origin.y
} set(newVal) { var tmpFrame : CGRect = frame
tmpFrame.origin.y = newVal
frame = tmpFrame
}
} // height
var height : CGFloat { get { return frame.size.height
} set(newVal) { var tmpFrame : CGRect = frame
tmpFrame.size.height = newVal
frame = tmpFrame
}
} // width
var width : CGFloat { get { return frame.size.width
} set(newVal) { var tmpFrame : CGRect = frame
tmpFrame.size.width = newVal
frame = tmpFrame
}
} // left
var left : CGFloat { get { return x
} set(newVal) { x = newVal
}
} // right
var right : CGFloat { get { return x + width
} set(newVal) { x = newVal - width
}
} // top
var top : CGFloat { get { return y
} set(newVal) { y = newVal
}
} // bottom
var bottom : CGFloat { get { return y + height
} set(newVal) { y = newVal - height
}
} var centerX : CGFloat { get { return center.x
} set(newVal) { center = CGPoint(x: newVal, y: center.y)
}
} var centerY : CGFloat { get { return center.y
} set(newVal) { center = CGPoint(x: center.x, y: newVal)
}
} var middleX : CGFloat { get { return width /
}
} var middleY : CGFloat { get { return height /
}
} var middlePoint : CGPoint { get { return CGPoint(x: middleX, y: middleY)
}
}
}

简单设置x/y/width/height

import UIKit

extension UIView {

    //设置随机背景色
func backgroundColorRandom(){ self.backgroundColor = UIColor(red: CGFloat(CGFloat(random())/CGFloat(RAND_MAX)), green: CGFloat(CGFloat(random())/CGFloat(RAND_MAX)), blue: CGFloat(CGFloat(random())/CGFloat(RAND_MAX)), alpha: )
} var x : CGFloat!{
get{return self.frame.origin.x }
set(newX){
var rect : CGRect! = self.frame
rect.origin.x = newX
self.frame = rect
} } var y : CGFloat!{
get{
return self.frame.origin.y
}
set(newY){
var rect : CGRect! = self.frame
rect.origin.y = newY
self.frame = rect
} } var width : CGFloat!{
get{
return self.frame.size.width
}
set(newW){
var rect : CGRect! = self.frame
rect.size.width = newW
self.frame = rect
} } var height : CGFloat!{
get{
return self.frame.size.height
}
set(newH){
var rect : CGRect! = self.frame
rect.size.height = newH
self.frame = rect
} } }

相关链接:swift关于UIView设置frame值的extension