改变UIView位置的简单方法?
我使用以下代码更改 UIView 的位置,而不更改视图的大小。
CGRect f = aView.frame;
f.origin.x = 100; // new x
f.origin.y = 200; // new y
aView.frame = f;
有没有更简单的方法来仅更改视图位置?
I change the position of a UIView with following codes without changing size of the view.
CGRect f = aView.frame;
f.origin.x = 100; // new x
f.origin.y = 200; // new y
aView.frame = f;
Is there more simple way to change only the view position?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
或
编辑:
我还没有编译这个,但它应该可以工作:
or
or
Edit:
I didn't compile this yet, but it should work:
我也有同样的问题。我制作了一个简单的 UIView 类别来解决这个问题。
.h.m
I had the same problem. I made a simple UIView category that fixes that.
.h
.m
UIView 也有一个 center 属性。如果您只想移动位置而不是调整大小,则可以更改它 - 例如:
aView.center = CGPointMake(50, 200);
否则,您将按照您发布的方式进行操作。
UIView's also have a
center
property. If you just want to move the position rather than resize, you can just change that - eg:aView.center = CGPointMake(50, 200);
Otherwise you would do it the way you posted.
我发现了一种类似的方法(它也使用了一个类别),gcamp的答案对我帮助很大 这里。在您的情况下,就像这样简单:
但是如果您想要水平居中并向左显示另一个视图,您可以简单地:
I found a similar approach (it uses a category as well) with gcamp's answer that helped me greatly here. In your case is as simple as this:
but if you want for example to centre horizontal and to the left with another view you can simply:
在使用自动布局的情况下,所选答案中的解决方案不起作用。如果您对视图使用自动布局,请查看此答案< /a>.
The solution in the selected answer does not work in case of using Autolayout. If you are using Autolayout for views take a look at this answer.
CGRectOffset
此后已替换为实例方法offsetBy
。https://developer.apple.com/reference/coregraphics/cgrect/1454841- offsetby
例如,以前的内容
现在是
CGRectOffset
has since been replaced with the instance methodoffsetBy
.https://developer.apple.com/reference/coregraphics/cgrect/1454841-offsetby
For example, what used to be
would now be
在我的工作中我们不使用宏。所以@TomSwift 提供的解决方案给了我启发。我看到了 CGRectMake 的实现并创建了相同的 CGRectSetPos 但没有宏。
使用时我只放置框架,X和Y
为我工作^_^
In my work we not use macros. So the solution provide by @TomSwift inspired to me. I see the implementation for CGRectMake and create the same CGRectSetPos but without macros.
To use I only put frame, X and Y
Work for me ^_^
如果有人需要轻型
Swift
扩展来轻松更改UIView
边距 - 您可以使用 这个If anybody needs light
Swift
extension to changeUIView
margins easily - you can use this@TomSwift Swift 3 答案
或
或
@TomSwift Swift 3 answer
Or
Or
迅速
swift
这是 Swift 3 的答案,适合任何寻找的人,因为 Swift 3 不接受“Make”。
Here is the Swift 3 answer for anyone looking since Swift 3 does not accept "Make".
其他方式:
这我保存尺寸参数并仅更改原点。
Other way:
This i save size parameters and change origin only.