如何以编程方式更改 UIView 的“原点”(如 Xcode 中标记的)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13206113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically change a UIView's "origin" (as labeled in Xcode)?
提问by Luther Baker
You will notice the red "+" / "arrows" glyph in the attached screenshot. It is easy enough to change this "origin" point in Xcode. Is there alsoa way to do this programmatically or is this entirely an Xcode abstraction?
您会注意到所附屏幕截图中的红色“+”/“箭头”字形。在 Xcode 中更改这个“原点”点很容易。有也一个以编程方式做到这一点,或者这是一个完全抽象的Xcode?
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.
例如,我想以编程方式创建一个 UILabel 并通过计算右下角坐标来定位它。在 Xcode 中,我会简单地确保红色“+”位于右下角的网格点上,并根据该“原点”定义 X、Y、宽度和高度参数。
回答by rob mayoff
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);
I would recommend just doing that.
我会建议这样做。
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:
但如果你愿意,你可以转而进入较低的层次。每个视图都有一个核心动画层,它实际管理视图的屏幕外观。图层有一个anchorPoint
属性,默认是(0.5, 0.5),代表图层的中心。您可以将anchorPoint
右下角的 (1, 1) 设置为:
label.layer.anchorPoint = CGPointMake(1, 1);
Now the label's center
actually controls the location of its lower right corner, so you can set it directly:
现在label的center
实际控制的是它的右下角的位置,所以可以直接设置:
label.center = somePoint; // actually sets the lower right corner
You'll need to add the QuartzCore
framework to your target and import <QuartzCore/QuartzCore.h>
to modify the anchorPoint
property.
您需要将QuartzCore
框架添加到目标并导入<QuartzCore/QuartzCore.h>
以修改anchorPoint
属性。
回答by Bad_APPZ
myObject.origin = CGPointMake (0.0,0.0);