在iOS中编码UIButton时避免重复代码

时间:2011-09-09 22:38:33

标签: ios uibutton uilabel

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

当您每次想要创建新按钮时都必须完成此过程时,这非常繁琐。简化此过程的最佳方法是什么,所以在编码按钮时我不必一遍又一遍地重复自己?

感谢。

1 个答案:

答案 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];