使用此代码:
// create a NEW button
self.badgeIndicatorView = [[UIButton alloc] initWithFrame:CGRectMake(self.friendsButton.frame.size.width-15, 5, 10, 10)];
self.badgeIndicatorView.backgroundColor = [UIColor redColor];
// friendsButton CANNOT contain the button you just created
BOOL doesContain = [self.friendsButton.subviews containsObject:self.badgeIndicatorView];
你会想检查friendsButton是否已经有一个子视图按钮。
附带说明,更好的方法是创建一个子类,在 init 上添加 badgeIndicatorView 按钮并将其设置为 hidden。然后,根据需要显示或隐藏它。
编辑
这一行:
self.badgeIndicatorView = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, 100, 40)];
创建一个NEW按钮并分配它给self.badgeIndicatorView。
如果一个按钮已被创建并分配给self.badgeIndicatorView,则新按钮将不等于旧按钮。旧按钮仍然存在,但不再分配给self.badgeIndicatorView。
查看它的简单方法...运行此代码:
self.badgeIndicatorView = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, 100, 40)];
// log description of self.badgeIndicatorView
NSLog(@"1: %@", self.badgeIndicatorView.debugDescription);
self.badgeIndicatorView = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, 100, 40)];
// log description of self.badgeIndicatorView
NSLog(@"2: %@", self.badgeIndicatorView.debugDescription);
self.badgeIndicatorView = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, 100, 40)];
// log description of self.badgeIndicatorView
NSLog(@"3: %@", self.badgeIndicatorView.debugDescription);
调试输出将与此类似 - 请注意对象地址不同(意味着您创建了 3 个按钮):
1: <UIButton: 0x7f997310e310; frame = (20 10; 100 40); opaque = NO; layer = <CALayer: 0x600002208000>>
2: <UIButton: 0x7f9951f09be0; frame = (20 10; 100 40); opaque = NO; layer = <CALayer: 0x600002275e60>>
3: <UIButton: 0x7f99730065a0; frame = (20 10; 100 40); opaque = NO; layer = <CALayer: 0x600002262760>>
因此,分配给self.badgeIndicatorView 的新按钮实例将与已创建并添加到self.friendsButton 的按钮实例不同。
您可以通过检查 self.badgeIndicatorView 是否不是 nil 来简化事情......这意味着它已经被创建并添加了:
if (!self.badgeIndicatorView) {
// create badgeIndicatorView and add it to self.friendsButton
} else {
// badgeIndicatorView already exists!
}