Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

objective c - iOS frame change one property (eg width)

This question was originally asked for the objective-c programming language. At the time of writing, swift didn't even exist yet.

Question

Is it possible to change only one property of a CGRect ?

For example:

self.frame.size.width = 50;

instead of

self.frame = CGRectMake(self.frame.origin.x, 
                        self.frame.origin.y, 
                        self.frame.size.width, 
                        50);

of course I understand that self.frame.size.width is read only so I'm wondering how to do this?

CSS ANALOGY proceed at your own risk

for those of you who are familiar with CSS, the idea is very similar to using:

margin-left: 2px;

instead of having to change the whole value:

margin: 5px 5px 5px 2px;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...