知识点工具文章

iOS UISwitch 添加文字 (onImage)

2020-06-19  本文已影响0人  rocky_tt
截屏2020-06-18下午6.03.29.png

在小白点上添加一个文字
第一步:找到小白点那个控件
第二步:把我们自己的文字Label添加上去(当然也可以添加图片)

_barrageSwitch = [[UISwitch alloc] init];
_barrageSwitch.transform = CGAffineTransformMakeScale(0.7, 0.7);
_barrageSwitch.onTintColor = [UIColor qmui_colorWithHexString:@"#FF5D7C"];
_barrageSwitch.on = YES;
//iOS12上立即添加Label后不显示,可能是系统替换了新的UIImageView
//导致添加的Label不显示,这里加上延时即可
//iOS13上不需要延时,其它版本未知,自行测试
//Label自己保存,根据开关状态改变文字颜色
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     NSArray * sub1 = self.barrageSwitch.subviews;
            UIImageView * onImg = nil;
            for (UIView * v1 in sub1) {
                NSArray * sub2 = v1.subviews;
                //iOS12在这里
                for (UIView * v2 in sub2) {
                    if ([v2 isKindOfClass:UIImageView.class] && v2.width == 43 && v2.height == 43) {
                        onImg = (UIImageView *)v2;
                        break;
                    }
                    //iOS13在这里
                    NSArray * sub3 = v2.subviews;
                    for (UIView * v3 in sub3) {
                        if ([v3 isKindOfClass:UIImageView.class] && v3.width == 43 && v3.height == 43) {
                            onImg = (UIImageView *)v3;
                            break;
                        }
                    }
                }
            }
            if (onImg) {
                UILabel * danmu = [[UILabel alloc] initWithFrame:CGRectMake(8, 5, 27, 27)];
                danmu.backgroundColor = [UIColor whiteColor];
                danmu.layer.cornerRadius = danmu.height * 0.5;
                danmu.layer.masksToBounds = YES;
                danmu.textColor = [UIColor qmui_colorWithHexString:@"#FF5D7C"];
                danmu.textAlignment = NSTextAlignmentCenter;
                danmu.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
                danmu.text = @"弹";
                [onImg addSubview:danmu];
                self.tanLabel = danmu;
            }
        });
//把系统的那个小白点图片保存到本地测量实际大小
//        NSString * path = [NSString stringWithFormat:@"%@/onImg.png",NSHomeDirectory()];
//        NSLog(@"%@",path);
//        [[NSFileManager defaultManager] createFileAtPath:path contents:UIImagePNGRepresentation(onImg.image) attributes:nil];
//        NSLog(@"%@",path);
//经实际测量得到小白点范围是(8, 5, 27, 27)
//然后自己添加UILabel上去,监听选中状态,可以自行更改颜色
if (onImg) {
    UILabel * danmu = [[UILabel alloc] initWithFrame:CGRectMake(8, 5, 27, 27)];
    danmu.backgroundColor = [UIColor whiteColor];
    danmu.layer.cornerRadius = danmu.height * 0.5;
    danmu.layer.masksToBounds = YES;
    danmu.textColor = [UIColor qmui_colorWithHexString:@"#FF5D7C"];
    danmu.textAlignment = NSTextAlignmentCenter;
    danmu.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    danmu.text = @"弹";
    [onImg addSubview:danmu];
    self.tanLabel = danmu;
}
上一篇下一篇

猜你喜欢

热点阅读