Ios 更改UIView位置的简单方法?
我使用以下代码更改UIView的位置,而不更改视图的大小Ios 更改UIView位置的简单方法?,ios,layout,uiview,frame,cgrect,Ios,Layout,Uiview,Frame,Cgrect,我使用以下代码更改UIView的位置,而不更改视图的大小 CGRect f = aView.frame; f.origin.x = 100; // new x f.origin.y = 200; // new y aView.frame = f; 是否有更简单的方法仅更改视图位置?UIView也有一个center属性。如果您只想移动位置而不是调整大小,您可以更改它-例如: aView.center=CGPointMake(50200) 否则你会按照你发布的方式来做 aView.frame =
CGRect f = aView.frame;
f.origin.x = 100; // new x
f.origin.y = 200; // new y
aView.frame = f;
是否有更简单的方法仅更改视图位置?UIView也有一个
center
属性。如果您只想移动位置而不是调整大小,您可以更改它-例如:
aView.center=CGPointMake(50200)代码>
否则你会按照你发布的方式来做
aView.frame = CGRectMake(100, 200, aView.frame.size.width, aView.frame.size.height);
或
或
编辑:
我还没有编译这个,但应该可以:
#define CGRectSetPos( r, x, y ) CGRectMake( x, y, r.size.width, r.size.height )
aView.frame = CGRectSetPos( aView.frame, 100, 200 );
我也有同样的问题。我制作了一个简单的UIView类别来修复这个问题
h
我发现了一个类似的方法(它也使用了一个类别),gcamp的答案对我帮助很大。在您的情况下,简单如下:
aView.topLeft = CGPointMake(100, 200);
但是,如果您想以另一个视图水平居中并向左,您可以简单地:
aView.topLeft = anotherView.middleLeft;
在我的工作中,我们不使用宏。因此@TomSwift提供的解决方案启发了我。我看到了CGRectMake的实现,并创建了相同的CGRectSetPos,但没有宏
CG_INLINE CGRect
CGRectSetPos(CGRect frame, CGFloat x, CGFloat y)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = frame.size.width; rect.size.height = frame.size.height;
return rect;
}
为了使用,我只放了框架,X和Y
viewcontroller.view.frame = CGRectSetPos(viewcontroller.view.frame, 100, 100);
为我工作^ ^如果使用自动布局,所选答案中的解决方案不起作用。如果您正在使用视图自动布局,请查看此项。如果任何人需要lightSwift
扩展来轻松更改UIView
页边距,您可以使用
以下是Swift 3的答案,因为Swift 3不接受“Make”
CGRectOffset
已被实例方法offsetBy
取代
例如,过去是什么
aView.frame = CGRectOffset(aView.frame, 10, 10)
现在应该是
aView.frame = aView.frame.offsetBy(dx: CGFloat(10), dy: CGFloat(10))
其他方式:
CGPoint position = CGPointMake(100,30);
[self setFrame:(CGRect){
.origin = position,
.size = self.frame.size
}];
我只保存尺寸参数并更改原点。@TomSwift 3 answer
aView.center = CGPoint(x: 150, y: 150); // set center
或
或
swift
view.frame = view.frame.offsetBy(dx: offsetX, dy: offsetY)
我想我们在同一时间输入了同一个东西。我喜欢尝试先得到最好答案的兴奋。耶,我也向上投票。它减少了胡言乱语。乱七八糟的我现在要花在别的东西上了。对于Swift 3:aView.frame=aView.frame.offsetBy(dx:100,dy:100)有没有办法使这个转换动画化-它看起来相当不和谐。我最终制作了完全相同的类方法,但没有想到将它附加到原始UIView类中+谢谢你的实用和聪明!如果您在Swift
中需要类似的东西,请随意使用我检查了CGRectMake的原始实现,这就是他们(苹果)的方式。注意:如果你使用的是自动布局,它是不起作用的。
view.top = 16
view.right = self.width
view.bottom = self.height
self.height = view.bottom
aView.center = CGPoint(x: 200, Y: 200)
aView.frame = CGRectOffset(aView.frame, 10, 10)
aView.frame = aView.frame.offsetBy(dx: CGFloat(10), dy: CGFloat(10))
CGPoint position = CGPointMake(100,30);
[self setFrame:(CGRect){
.origin = position,
.size = self.frame.size
}];
aView.center = CGPoint(x: 150, y: 150); // set center
aView.frame = CGRect(x: 100, y: 200, width: aView.frame.size.width, height: aView.frame.size.height ); // set new position exactly
aView.frame = aView.frame.offsetBy(dx: CGFloat(10), dy: CGFloat(10)) // offset by an amount
view.frame = view.frame.offsetBy(dx: offsetX, dy: offsetY)