如何以编程方式更改 UIView 的“原点"(如 Xcode 中标记的那样)? [英] How to programmatically change a UIView's "origin" (as labeled in Xcode)?

查看:27
本文介绍了如何以编程方式更改 UIView 的“原点"(如 Xcode 中标记的那样)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您会注意到附加屏幕截图中的红色+"/箭头"字形.在 Xcode 中更改这个原点"点很容易.是否有以编程方式执行此操作的方法,或者这完全是 Xcode 抽象?

You will notice the red "+" / "arrows" glyph in the attached screenshot. It is easy enough to change this "origin" point in Xcode. Is there also a way to do this programmatically or is this entirely an Xcode abstraction?

例如,我想以编程方式创建一个 UILabel 并通过计算右下角坐标来定位它.在 Xcode 中,我会简单地确保红色+"位于右下角的网格点上,并根据该原点"定义 X、Y、宽度和高度参数.

For instance, I want to programmatically create a UILabel and position it by calculating the lower right hand coordinate. In Xcode, I would simply make sure that the red "+" is on the bottom right grid point and define the X, Y, Width and Height parameters with that "origin" in mind.

推荐答案

如果您不使用自动布局,您可以通过设置标签(或任何视图)的中心来在代码中定位标签(或任何视图).所以如果你知道你想要标签的右下角在哪里,你可以减去标签的宽度和高度的一半来计算它的中心应该在哪里:

If you're not using autolayout, you can position a label (or any view) in code by setting its center. So if you know where you want the label's lower right corner to be, you can just subtract half the width and height of the label to compute where its center should be:

CGPoint lowerRight = somePoint;
CGRect frame = label.frame;
label.center = CGPointMake(lowerRight.x - frame.size.width / 2,
    lowerRight.y - frame.size.height / 2);

我建议就这样做.

但如果您愿意,您可以转而进入较低级别.每个视图都有一个核心动画层,它实际管理视图的屏幕外观.图层有一个 anchorPoint 属性,默认为 (0.5, 0.5),代表图层的中心.您可以将右下角的 anchorPoint 设置为 (1, 1):

But if you want, you can instead go to a lower level. Every view has a Core Animation layer, which is what actually manages the view's on-screen appearance. The layer has an anchorPoint property, which by default is (0.5, 0.5), representing the center of the layer. You can set the anchorPoint to (1, 1) for the lower-right corner:

label.layer.anchorPoint = CGPointMake(1, 1);

现在标签的center实际上控制了它的右下角的位置,所以可以直接设置:

Now the label's center actually controls the location of its lower right corner, so you can set it directly:

label.center = somePoint; // actually sets the lower right corner

您需要将 QuartzCore 框架添加到目标并导入 以修改 anchorPoint财产.

You'll need to add the QuartzCore framework to your target and import <QuartzCore/QuartzCore.h> to modify the anchorPoint property.

这篇关于如何以编程方式更改 UIView 的“原点"(如 Xcode 中标记的那样)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆