对于iOS编程和Objective-C,我一般都很陌生,所以这个问题可能已经被问过很多次了。总之:在iOS中对UIButton进行编码时避免重复代码
在我的iOS应用程序,我有我创建如下方式几个UIButtons:
UIButton *webButton = [UIButton buttonWithType:UIButtonTypeCustom];
[webButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
webButton.frame = CGRectMake(10, 315, 300, 44);
[webButton setBackgroundImage:[UIImage imageNamed:@"WebButton.png"] forState:UIControlStateNormal];
[webButton setBackgroundImage:[UIImage imageNamed:@"WebButtonPressed.png"] forState:UIControlStateHighlighted];
因为我希望按钮的标题是容易编辑,我再加入UILabels的按钮,而不是让它们成为用作按钮背景图像的图像的一部分。
UILabel *webLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 300, 15)];
webLabel.text = @"Some website";
webLabel.font = [UIFont boldSystemFontOfSize:16.0];
webLabel.textColor = [UIColor colorWithRed:62.0/255 green:135.0/255 blue:203.0/255 alpha:1];
webLabel.textAlignment = UITextAlignmentCenter;
webLabel.backgroundColor = [UIColor clearColor];
[webButton addSubview:webLabel];
[webLabel release];
当你每次想要创建一个新按钮时都必须经过这个过程,这会变得非常单调乏味。什么是简化这个过程的最好方法,所以在编码按钮时我不必一遍又一遍地重复自己。
谢谢。
约一个简单的子程序?没有真正需要花哨的子类或任何东西,只需将大部分逻辑放在常见的例程中。 –
如果您重复使用相同的颜色,您可以制作一份并共享它。 –