【发布时间】:2011-09-09 22:38:33
【问题描述】:
总的来说,我对 iOS 编程和 Objective-C 还很陌生,所以这个问题可能已经被问过几次了。无论如何:
在我的 iOS 应用程序中,我有几个 UIButton,我通过以下方式创建:
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];
由于我希望按钮的标题易于编辑,因此我将 UILabel 添加到按钮中,而不是让它们成为用作按钮背景图像的图像的一部分。
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];
当您每次想要创建一个新按钮时都必须执行此过程时,这会变得非常乏味。简化此过程的最佳方法是什么,这样我在编写按钮时就不必一遍又一遍地重复自己?
谢谢。
【问题讨论】:
-
一个简单的子程序怎么样?不需要花哨的子类或任何东西,只需将大部分逻辑放在通用例程中即可。
-
如果您反复使用相同的颜色,您可以复制一份并分享。