Addtarget for UIControlStateNormal 不起作用



我创建了一个名为SectionButton的自定义UIButton。

该按钮有 2 个图像,一个用于正常状态,另一个用于选定和突出显示状态。

该按钮还具有文本,当按下按钮时,必须调整标题边缘插图。

在 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

您正在传递控件状态来代替 ControlEvent,

[self addTarget:self action: @selector(buttonHighlighted:) forControlEvents: UIControlEventTouchDownInside];
[self addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];

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

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

最新更新