在iOS中设置框架的原点[英] Setting the origin of the frame in iOS

本文是小编为大家收集整理的关于在iOS中设置框架的原点的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我试图以编程方式设置帧的原点.

方法1:

button.frame.origin.y = 100;

方法2:

CGRect frame = button.frame;
frame.origin.y = 100;

我尝试了方法1,但它不起作用(显示出一个错误,说表达不可分配).方法2正在工作.为什么这样?

需要关于我做对的事情的指导.

推荐答案

您无法执行方法1的原因是因为框架的单个属性是只读的.但是,整个框架本身都是可写的/可分配的,因此您可以执行方法#2.

您甚至可以做这样的技巧:

CGRect newFrame = button.frame;
newFrame.origin.y += 100; // add 100 to y's current value
button.frame = newFrame;

其他推荐答案

你知道 button.frame.origin.y返回值.

如果您正在使用此错误,则会得到此错误...

表达式无法分配.

button.frame.origin.y = 100;

所以这是正确的方式

CGRect frame = button.frame;
frame.origin.y = 100;

否则您可以这样做...

button.frame = CGRectMake(button.frame.origin.x, 100, button.frame.size.width, button.frame.size.height)

其他推荐答案

这是因为如果您能够直接更改帧的原点或大小,则绕过Uiview Frame属性的Setter方法.由于多种原因,这将是不好的.

Uiview将没有机会就其框架的更改通知.但是它必须了解这些更改才能更新其子视图或重新绘制.

本文地址:https://www.itbaoku.cn/post/2091160.html

问题描述

I am trying to set the origin of the frame programmatically.

Method1:

button.frame.origin.y = 100;

Method 2:

CGRect frame = button.frame;
frame.origin.y = 100;

I tried method 1 but it is not working(showing an error saying Expression is not assignable). Method 2 is working. Why is this so?

Need guidance on what I am doing right.

推荐答案

The reason you can't do method #1 is because a frame's individual properties are read-only. However, the entire frame itself is writable/assignable, thus you can do method #2.

You can even do tricks like this:

CGRect newFrame = button.frame;
newFrame.origin.y += 100; // add 100 to y's current value
button.frame = newFrame;

其他推荐答案

You know button.frame.origin.y return a value.

if you are using this one so you will get this error...

Expression is not assignable.

button.frame.origin.y = 100;

So this is correct way

CGRect frame = button.frame;
frame.origin.y = 100;

otherwise you can do like this...

button.frame = CGRectMake(button.frame.origin.x, 100, button.frame.size.width, button.frame.size.height)

其他推荐答案

It's because if you were able to directly change a frame's origin or size, you would bypass the setter method of UIView's frame property. This would be bad for multiple reasons.

UIView would have no chance to be notified about changes to it's frame. But it has to know about these changes to be able to update it's subviews or redraw itself.