我创建了一个名为 SectionButton 的自定义 UIButton。
该按钮有 2 个图像,一个用于正常状态,另一个用于选定和突出显示状态。
该按钮也有一个文本,当按下按钮时,必须调整 TitleEdgesInset。
在 init 方法中,我添加了方法:
[self addTarget:self action: @selector(buttonHighlighted:) forControlEvents: UIControlStateHighlighted];
[self addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlStateNormal];
但是方法'buttonNormal:'从未被调用,所以我不能调整titleEdgeInsets 属性。
#import "SectionButton.h"
@implementation SectionButton
- (id)initWithFrame: (CGRect)frame andTitle: (NSString*)title andbaseImageName:(NSString*)imageBaseName
{
if (self = [super initWithFrame: frame])
{
// Create images for button
UIImage* normalImage = [UIImage imageNamed: imageBaseName ];
UIImage* downImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_selected",imageBaseName]];
// Set up button
[self setTitle: [title uppercaseString] forState: UIControlStateNormal]; // Will be used for all states
[self setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
[self.titleLabel setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];
[self setBackgroundImage: normalImage forState: UIControlStateNormal];
[self setBackgroundImage: downImage forState: UIControlStateHighlighted];
[self setContentEdgeInsets:UIEdgeInsetsMake(54, 0, 0, 0)];
[self addTarget: self action: @selector(buttonHighlighted:) forControlEvents: UIControlStateHighlighted];
[self addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlStateNormal];
}
return self;
}
- (void)buttonHighlighted: (id)sender
{
[self setTitleEdgeInsets:UIEdgeInsetsMake(0,0,-16,0)];
NSLog(@"button selected");
}
- (void) buttonNormal: (id)sender {
[self setTitleEdgeInsets:UIEdgeInsetsMake(0,0,0,0)];
NSLog(@"Button normal");
}
}
@end