UIControlStateNormal的Addtarget不起作用

时间:2012-12-17 11:32:35

标签: iphone ios uibutton uicontrolevents

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

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

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