2011-09-09 53 views
1

对于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]; 

当你每次想要创建一个新按钮时都必须经过这个过程,这会变得非常单调乏味。什么是简化这个过程的最好方法,所以在编码按钮时我不必一遍又一遍地重复自己。

谢谢。

+0

约一个简单的子程序?没有真正需要花哨的子类或任何东西,只需将大部分逻辑放在常见的例程中。 –

+0

如果您重复使用相同的颜色,您可以制作一份并共享它。 –

回答

2

我怀疑你想要做的是创建一个UIButton的子类。这样你就可以编写一次你的代码,但将它用于任意数量的按钮。东西有点像这样:

// in your .h file 

#import <UIKit/UIKit.h> 
@interface WebButton : UIButton 
+ (WebButton*) webButtonWithBackgroundImageNamed: (NSString*) imageName title: (NSString*) string andTarget: (id) target; 
@end 

// in your .m file 
#import "WebButton.h" 
@implementation WebButton 

+ (WebButton*) webButtonWithBackgroundImageNamed: (NSString*) imageName title: (NSString*) string andTarget: (id) target; 
{ 
    WebButton *webButton = [WebButton buttonWithType:UIButtonTypeCustom]; 
    [webButton addTarget:target action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    webButton.frame = CGRectMake(0, 0, 300, 44); 
    [webButton setBackgroundImage:[UIImage imageNamed: imageName] forState:UIControlStateNormal]; 
    [webButton setBackgroundImage:[UIImage imageNamed: [NSString stringWithFormat:@"%@pressed", imageName]] forState:UIControlStateHighlighted]; 

    UILabel *webLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 300, 15)]; 
    webLabel.text = string; 
    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]; 

    return webButton; 
} 

然后创建和添加按钮的视图的东西有点像这样:

WebButton* webButton = [WebButton webButtonWithBackgroundImageNamed:@"WebButton" title:@"testing" andTarget:self]; 
CGRect webButtonFrame = [webButton frame]; 
webButtonFrame.origin.x = 10; 
webButtonFrame.origin.y = 30; 
[webButton setFrame:webButtonFrame]; 
[[self window] addSubview:webButton]; 
如何
+0

工程就像一个魅力。谢谢! – wstr