自定义UIButton无法识别的选择器问题

时间:2015-04-28 19:17:46

标签: ios objective-c uibutton

我正在创建一个简单的UIButton子类。

.h文件:

@interface VUFollowButton : UIButton

/**
 Designated initializer

 @param follow Highlights the button if true
 */
+ (instancetype)buttonWithFollow:(BOOL)follow;

/*
 * Setting this bool to YES will highlight the button and change the text to "following"
 * Default is "follow"
 */
@property (nonatomic, assign) BOOL following;


@end

.m文件:

 #import "VUFollowButton.h"

@implementation VUFollowButton

+ (instancetype)buttonWithFollow:(BOOL)follow {

    VUFollowButton* followButton = (VUFollowButton*)[UIButton buttonWithType:UIButtonTypeCustom];
    [followButton setTitleEdgeInsets:UIEdgeInsetsMake(2., 8., 2., 8.)];
    followButton.layer.borderColor = [UIColor whitColor];
    followButton.layer.borderWidth = 2.0f;
    [followButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    followButton.titleLabel.font = [UIFont nationalBoldWithSize:17];
    followButton.following = follow;

    return followButton;
}

- (void)setFollowing:(BOOL)following {

    if (!following) {
        self.backgroundColor = [UIColor clearColor];
        [self setTitle:@"FOLLOW" forState:UIControlStateNormal];
    }
    else {
        self.backgroundColor = [UIColor blackColor];
        [self setTitle:@"FOLLOWING" forState:UIControlStateNormal];
    }
}

@end

但在followButton.following = follow;这一行,我得到了:

-[UIButton setFollowing:]: unrecognized selector sent to instance 0x7f9c10f809b0

如果我在该行之前设置断点,followButton在变量调试器中显示为VUFollowButton,并且具有名为following的属性。

我知道我在这里缺少一些基本的东西。

2 个答案:

答案 0 :(得分:3)

您正在实例化UIButton并将其投射到VUFollowButton。您返回的实例属于UIButton类型,它没有setFollowing:访问器方法或以下属性。以下属性可见的原因是因为您已将其转换为VUFollowButton类型。

<强> E.g。

VUFollowButton* followButton = (VUFollowButton*)[UIButton buttonWithType:UIButtonTypeCustom];

应该是:

VUFollowButton* followButton = [VUFollowButton buttonWithType:UIButtonTypeCustom];

答案 1 :(得分:0)

在以下一行

VUFollowButton* followButton = (VUFollowButton*)[UIButton buttonWithType:UIButtonTypeCustom];

您实际创建了UIButton。将其更改为

VUFollowButton* followButton = [self buttonWithType:UIButtonTypeCustom];