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

Ben*_*n-G 0 objective-c uibutton ios

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

Nic*_*ood 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
Run Code Online (Sandbox Code Playgroud)

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