一般来说,我对iOS编程和Objective-C非常陌生,所以这个问题可能已经被悄悄问过几次了。不管怎么说:
在我的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];当你每次想要创建一个新的按钮时都要经历这个过程,这会变得非常乏味。简化这个过程的最好方法是什么,这样我就不必在编写按钮代码时一遍又一遍地重复自己?
谢谢。
发布于 2011-09-10 08:04:59
我想你想要做的是创建一个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];https://stackoverflow.com/questions/7368174
复制相似问题