0

我创建了一个名为 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
4

2 回答 2

3

您正在传递控制状态而不是 ControlEvent,

[self addTarget:self action: @selector(buttonHighlighted:) forControlEvents: UIControlEventTouchDownInside];
[self addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];
于 2012-12-17T11:38:44.713 回答
1

您只需要调用该按钮的 1 个方法。

在该方法中,您需要根据按钮的当前状态执行代码。

于 2012-12-17T11:58:20.797 回答