自定义 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 的属性。

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

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

例如

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

应该是:

VUFollowButton* followButton = [VUFollowButton buttonWithType:UIButtonTypeCustom];

在下一行

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

你实际上创造了UIButton.将其更改为

VUFollowButton* followButton = [self buttonWithType:UIButtonTypeCustom];

最新更新