跟踪UIButton状态变化的解决方案

时间:2012-01-25 10:27:15

标签: ios objective-c uibutton

UIButton提供了许多与状态相关的设置(image,titleColor等)。 我已经手动将一个子视图添加到一个按钮,该按钮将响应按钮状态的变化。 我该怎么办?我应该尝试在状态变化上映射UIControlEvent吗?

1 个答案:

答案 0 :(得分:6)

你可以通过为按钮的选定和突出显示的属性添加KVO观察者来实现,但这比创建UIButton的子类并重载setSelectedsetHighlighted方法要复杂得多。你这样做是这样的:

//MyCustomButton.h

@interface MyCustomButton : UIButton

@end


//MyCustomButton.m

@implementation MyCustomButton

- (void)setUp
{
    //add my subviews here
}

- (id)initWithFrame:(CGRect)frame
{
    //this is called when you create your button in code
    if ((self = [super initWithFrame:frame]))
    {
        [self setUp];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    //this is called when you create your button in interface builder
    if ((self = [super initWithCoder:aDecoder]))
    {
        [self setUp];
    }
    return self;
}

- (void)setSelected:(BOOL)selected
{
    super.selected = selected;
    //update my subviews here
}

- (void)setHighlighted:(BOOL)highlighted
{
    super.highlighted = highlighted;
    //update my subviews here
}

@end

然后,您可以在代码中创建自定义按钮,或者在界面构建器中创建自定义按钮,方法是将常规UIButton拖到视图上,然后在检查器中将其类设置为MyCustomButton