ControlStateNormal的Addtarget不起作用

ControlStateNormal的Addtarget不起作用

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

最佳答案

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

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

关于iphone - UIControlStateNormal的Addtarget不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13913334/

10-11 00:47