记录一个坑的解决历程

156 阅读2分钟

声明一个按钮属性:

@property(nonatomic,strong)UIButton *valueBtn;

在页面初始化地方创建按钮:

self.valueBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, width)];
self.valueBtn.titleLabel.font = [UIFont systemFontOfSize:9];
self.valueBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
self.valueBtn.userInteractionEnabled = NO;
self.valueBtn.backgroundColor = RGBCOLOR(234,36,36);
[self.valueBtn setTitleColor:RGBCOLOR(255, 254, 254) forState:UIControlStateNormal];
[self addSubview:self.valueBtn];

自定义设置角标:

- (void)showBageValues:(NSInteger)bageValues{
    
    NSLog(@"-----showBageValues---%ld", bageValues);
    
    CGFloat width = 11;
    if (bageValues == 0) {
        self.valueBtn.hidden = YES;
        
        NSLog(@"-----valueBtn: %f---%f--%@", self.valueBtn.frame.size.height, self.valueBtn.frame.size.height, self.valueBtn);
        
    }else if (bageValues < 10){
        
        NSLog(@"---self.valueBtn.hidden = NO");
        
        self.valueBtn.hidden = NO;
        CGRect frame = self.valueBtn.frame;
        frame.size = CGSizeMake(width, width);
        self.valueBtn.frame = frame;
        self.valueBtn.layer.masksToBounds = YES;
        self.valueBtn.layer.cornerRadius = width/2;
        [self.valueBtn setTitle:[NSString stringWithFormat:@"%lu",bageValues] forState:UIControlStateNormal];
    }else if(bageValues < 100){
        self.valueBtn.hidden = NO;
        CGRect frame = self.valueBtn.frame;
        frame.size = CGSizeMake(width*1.6, width*1.1);
        self.valueBtn.frame = frame;
        self.valueBtn.layer.masksToBounds = YES;
        self.valueBtn.layer.cornerRadius = 6;
        [self.valueBtn setTitle:[NSString stringWithFormat:@"%lu",bageValues] forState:UIControlStateNormal];
    }else if (bageValues > 99){
        self.valueBtn.hidden = NO;
        CGRect frame = self.valueBtn.frame;
        frame.size = CGSizeMake(width*2.2, width*1.2);
        self.valueBtn.frame = frame;
        self.valueBtn.layer.masksToBounds = YES;
        self.valueBtn.layer.cornerRadius = 7;
        [self.valueBtn setTitle:[NSString stringWithFormat:@"99+"] forState:UIControlStateNormal];
    }
}

问题描述: 登录A账号,假如获取消息角标数量为6,切换成B账号登录,假如B账户没有消息,则角标应该为0,即不显示角标,而此时角标却仍显示为6;

分析: 刚开始判断以为是退出登录时 没有清除相关数据,因为消息是集成的环信,所以就一直查看环信相关文档和Demo中相关代码,奇怪的是几乎没有类似的问题。 打断点调试,发现切换账号后,此时代码是走了如下代码的

if (bageValues == 0) {
        self.valueBtn.hidden = YES;
        
        NSLog(@"-----valueBtn: %f---%f--%@", self.valueBtn.frame.size.height, self.valueBtn.frame.size.height, self.valueBtn);
        
    }

然后就想知道为什么明明设置了hidden为YES,却没有隐藏。

解决: 退出A账号 切换B账号或者不切换账号仍登录此账号,会先走初始化方法

self.valueBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, width)];

这样的写法会又创建一个按钮,而虽然走了self.valueBtn.hidden = YES;只是将新创建的按钮隐藏了,之前创建的那个valueBtn并没有隐藏,如果打印它们的地址,会发现两个不是同一个。因此,创建按钮修改为懒加载。