iOS框架改变一个属性(例如宽度) [英] iOS frame change one property (eg width)
问题描述
这个问题最初是针对objective-c编程语言提出的。在撰写本文时,swift尚未存在。
是是否可以仅更改 CGRect
的一个属性?
Is it possible to change only one property of a CGRect
?
例如:
self.frame.size.width = 50;
而不是
self.frame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
self.frame.size.width,
50);
当然我明白 self.frame.size.width
是只读所以我想知道如何做到这一点?
of course I understand that self.frame.size.width
is read only so I'm wondering how to do this?
CSS ANALOGY 对于那些熟悉 CSS
的人来说,请自担风险
CSS ANALOGY proceed at your own risk
与使用非常相似:
margin-left: 2px;
而不必更改整个值:
margin: 5px 5px 5px 2px;
推荐答案
回答你原来的问题:是的,有可能只更改 CGRect
结构中的一个成员。此代码不会引发任何错误:
To answer your original question: yes, it's possible to change just one member of a CGRect
structure. This code throws no errors:
myRect.size.width = 50;
什么是不可能,但是,更改单个成员一个 CGRect
,它本身就是另一个对象的属性。在这种非常常见的情况下,您必须使用临时局部变量:
What is not possible, however, is to change a single member of a CGRect
that is itself a property of another object. In that very common case, you would have to use a temporary local variable:
CGRect frameRect = self.frame;
frameRect.size.width = 50;
self.frame = frameRect;
原因是使用属性访问器 self.frame =。 ..
等同于 [self setFrame:...]
,此访问者总是需要一个完整的 CGRect
。在这种情况下,使用Objective-C属性点表示法混合C风格的 struct
访问不起作用。
The reason for this is that using the property accessor self.frame = ...
is equivalent to [self setFrame:...]
and this accessor always expects an entire CGRect
. Mixing C-style struct
access with Objective-C property dot notation does not work well in this case.
这篇关于iOS框架改变一个属性(例如宽度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!