在OC中是不能UI元素.位置/大小属性 = XXX
这种形式直接赋值的,所以需要给UIView建立分类才能实现上述赋值方法;
而在Swift中,是可以对元素的大小/位置属性直接赋值的,但是也要写很长一串,Swift也可通过建立分类达到和OC一样的效果。
在这里只列出:origin、size、x、y、width、height、centerX、centerY的赋值写法
- OC版本(需要在.h中声明对应属性)
- (void)setWidth:(CGFloat)width
{
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (void)setHeight:(CGFloat)height
{
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
- (void)setX:(CGFloat)x
{
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (void)setY:(CGFloat)y
{
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (void)setSize:(CGSize)size
{
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
- (void)setCenterX:(CGFloat)centerX
{
CGPoint center = self.center;
center.x = centerX;
self.center = center;
}
- (void)setCenterY:(CGFloat)centerY
{
CGPoint center = self.center;
center.y = centerY;
self.center = center;
}
- (CGFloat)centerX
{
return self.center.x;
}
- (CGFloat)centerY
{
return self.center.y;
}
-(CGSize)size
{
return self.frame.size;
}
-(CGFloat)width
{
return self.frame.size.width;
}
-(CGFloat)height
{
return self.frame.size.height;
}
-(CGFloat)x
{
return self.frame.origin.x;
}
-(CGFloat)y
{
return self.frame.origin.y;
}
- (CGPoint)origin {
return self.frame.origin;
}
- (void)setOrigin:(CGPoint)origin {
CGRect frame = self.frame;
frame.origin = origin;
self.frame = frame;
}
- Swift版本(此段写于 2016/12/16 适用于swift 3.0):
public var x : CGFloat {
get {
return self.frame.origin.x
}
set {
var f = self.frame
f.origin.x = newValue
self.frame = f
}
}
/// y
public var y : CGFloat {
get {
return self.frame.origin.y
}
set {
var f = self.frame
f.origin.y = newValue
self.frame = f
}
}
/// width
public var width : CGFloat {
get {
return self.frame.size.width
}
set {
var f = self.frame
f.size.width = newValue
self.frame = f
}
}
/// height
public var height : CGFloat {
get {
return self.frame.size.height
}
set {
var f = self.frame
f.size.height = newValue
self.frame = f
}
}
/// origin
public var origin : CGPoint {
get {
return self.frame.origin
}
set {
var f = self.frame
f.origin = newValue
self.frame = f
}
}
/// size
public var size : CGSize {
get {
return self.frame.size
}
set {
var f = self.frame
f.size = newValue
self.frame = f
}
}
/// centerX
public var centerX : CGFloat {
get {
return self.center.x
}
set {
var c = self.center
c.x = newValue
self.center = c
}
}
/// centerY
public var centerY : CGFloat {
get {
return self.center.y
}
set {
var c = self.center
c.y = newValue
self.center = c
}
}
网友评论