在Objective-C中以编程方式创buildUI元素

我一直在努力自动创buildUI元素的一些方面,并创build了这个似乎工作的方法:

- (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; } 
  1. 这个实现有什么不对吗?

  2. 而不是使用方法,只用简单的旧函数就可以实现同样的事情吗? 需要指出参数名称xPos:30 yPos:100 width:100 height:100等有点冗长

会很高兴能够做到这样的事情:

 button = createButton(30, 100, 100, 30, @"autoButton", NSTextAlignmentCenter, [UIColor blackColor], [UIColor yellowColor]); 

这是可行的吗?

  1. 很好,除了传递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; } 
  2. 好的,使用一个函数或方法。 由你决定。 只要你不需要self介入,一个function就可以工作。

     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]; } 

您可以使用Objective-c中的类别内置function
1. 苹果纪录片,用于定制类
2. 分类教程