UIButton 例子
UICatalog例子
例子中得方法:
+ (UIButton *)buttonWithTitle: (NSString *)title target:(id)target selector:(SEL)selector frame:(CGRect)frame image:(UIImage *)image imagePressed:(UIImage *)imagePressed darkTextColor:(BOOL)darkTextColor{ UIButton *button = [[UIButton alloc] initWithFrame:frame]; // or you can do this: // UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; // button.frame = frame; button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; [button setTitle:title forState:UIControlStateNormal]; if (darkTextColor) { [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; } else { [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; } UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0]; [button setBackgroundImage:newImage forState:UIControlStateNormal]; UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0]; [button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted]; [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside]; // in case the parent view draws with a custom color or gradient, use a transparent color button.backgroundColor = [UIColor clearColor]; return button;}
用法:
- (void)createGrayButton{ // create the UIButtons with various background images // white button: UIImage *buttonBackground = [UIImage imageNamed:@"whiteButton.png"]; UIImage *buttonBackgroundPressed = [UIImage imageNamed:@"blueButton.png"]; CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight); grayButton = [ButtonsViewController buttonWithTitle:@"Gray" target:self selector:@selector(action:) frame:frame image:buttonBackground imagePressed:buttonBackgroundPressed darkTextColor:YES];}