我一直在努力自动化创建UI元素的某些方面,并创建了这个似乎有用的方法:
- (void) viewDidLoad
{
[super viewDidLoad];
button = [self createButton:button xPos:30 yPos:100 width:100 height:30 caption:@"autoButton" textPos:NSTextAlignmentCenter textClr:[UIColor blackColor] backClr:[UIColor yellowColor]];
[self.view addSubview: button];
}
- (UIButton *) createButton:(UIButton *)control xPos:(CGFloat)x yPos:(CGFloat)y width:(CGFloat)width height:(CGFloat)height caption:(NSString *)caption textPos:(NSTextAlignmentCenter)textPosition textClr:(UIColor *)textColor backClr:(UIColor *)backColor
{
control = [[UIButton alloc] initWithFrame: CGRectMake(x, y, width, height)];
[control setTitle:caption forState:UIControlStateNormal];
control.titleLabel.textAlignment = textPosition;
control.backgroundColor = backColor;
[control setTitleColor: textColor forState:UIControlStateNormal];
return control;
}
此实施有什么不对吗?
不是使用方法,是否可以用简单的旧函数实现相同的功能?如果必须指出参数名称, xPos:30 yPos:100宽度:100高度:100等等
,这有点啰嗦。很高兴能够做到这样的事情:
button = createButton(30, 100, 100, 30, @"autoButton", NSTextAlignmentCenter, [UIColor blackColor], [UIColor yellowColor]);
这可行吗?
答案 0 :(得分:3)
很好,除了传递button
参数没有意义。只需返回UIButton
对象。
- (void) viewDidLoad
{
[super viewDidLoad];
button = [self createButtonWithxPos:30 yPos:100 width:100 height:30 caption:@"autoButton" textPos:NSTextAlignmentCenter textClr:[UIColor blackColor] backClr:[UIColor yellowColor]];
[self.view addSubview: button];
}
- (UIButton *) createButtonWithxPos:(CGFloat)x yPos:(CGFloat)y width:(CGFloat)width height:(CGFloat)height caption:(NSString *)caption textPos:(NSTextAlignmentCenter)textPosition textClr:(UIColor *)textColor backClr:(UIColor *)backColor
{
UIButton *control = [[UIButton alloc] initWithFrame: CGRectMake(x, y, width, height)];
[control setTitle:caption forState:UIControlStateNormal];
control.titleLabel.textAlignment = textPosition;
control.backgroundColor = backColor;
[control setTitleColor: textColor forState:UIControlStateNormal];
return control;
}
好的,使用功能或方法。由你决定。只要您不需要self
,就可以使用一个函数。
UIButton *createButton(CGFloat x, CGFloat y, CGFloat width, CGFloat height, NSString *caption, NSTextAlignmentCenter textPosition, UIColor *textColor, UIColor *backColor) {
UIButton *control = [[UIButton alloc] initWithFrame: CGRectMake(x, y, width, height)];
[control setTitle:caption forState:UIControlStateNormal];
control.titleLabel.textAlignment = textPosition;
control.backgroundColor = backColor;
[control setTitleColor: textColor forState:UIControlStateNormal];
return control;
}
- (void) viewDidLoad
{
[super viewDidLoad];
button = createButton(30, 100, 100, 30, @"autoButton", NSTextAlignmentCenter, [UIColor blackColor], [UIColor yellowColor]);
[self.view addSubview: button];
}
答案 1 :(得分:1)
您可以使用Objective-c 中的内置功能类别:
1。Apple documentary for customising classes
2。Categories tutorial