改变CGRect(或任何结构体)? [英] Alter CGRect (or any struct)?
问题描述
我在代码中做了很多:
self.sliderOne.frame = CGRectMake(newX, 0, self.sliderOne.frame.size.width, self.sliderOne.frame.size.height);
有没有办法避免这个繁琐的代码?我试过这样的事情:
Is there any way to avoid this tedious code? I have tried this type of thing:
self.sliderOne.frame.origin.x = newX;
但我得到一个作为分配左操作数所需的左值$ c>错误。
but I get a Lvalue required as left operand of assignment
error.
推荐答案
我终于跟着@Dave DeLong的建议,并提出了一个类别。所有你需要做的是在任何想要利用它的类中导入它。
I finally followed @Dave DeLong's suggestion and made a category. All you have to do is import it in any class that wants to take advantage of it.
UIView + AlterFrame.h
#import <UIKit/UIKit.h>
@interface UIView (AlterFrame)
- (void) setFrameWidth:(CGFloat)newWidth;
- (void) setFrameHeight:(CGFloat)newHeight;
- (void) setFrameOriginX:(CGFloat)newX;
- (void) setFrameOriginY:(CGFloat)newY;
@end
UIView + AlterFrame.m
#import "UIView+AlterFrame.h"
@implementation UIView (AlterFrame)
- (void) setFrameWidth:(CGFloat)newWidth {
CGRect f = self.frame;
f.size.width = newWidth;
self.frame = f;
}
- (void) setFrameHeight:(CGFloat)newHeight {
CGRect f = self.frame;
f.size.height = newHeight;
self.frame = f;
}
- (void) setFrameOriginX:(CGFloat)newX {
CGRect f = self.frame;
f.origin.x = newX;
self.frame = f;
}
- (void) setFrameOriginY:(CGFloat)newY {
CGRect f = self.frame;
f.origin.y = newY;
self.frame = f;
}
@end
我可以把方法使用块...我会很快在某个时候做,我希望。
I could DRY up the methods using blocks... I'll do that at some point soon, I hope.
稍后:我刚刚注意到 CGRectOffset
和 CGRectInset
,所以这个类别可以被清理一下(如果没有完全消除)。
Later: I just noticed CGRectOffset
and CGRectInset
, so this category could be cleaned up a bit (if not eliminated altogether).
这篇关于改变CGRect(或任何结构体)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!