当前位置: 首页 > 工具软件 > iOS7Colors > 使用案例 >

ios 给UIView类控件添加渐变颜色的注意事项

白淇
2023-12-01

通常在我们的日常开发中,会遇到一下需求,要实现某个控件的背景色是渐变效果的。例如:实现一个按钮的渐变色。通常我们的日常写法:

-(UIButton *)verifyBtn{
    if (!_verifyBtn) {
        _verifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _verifyBtn.frame = CGRectMake(64, ScreenHeight - NaviBarHeight -TabbarHeight - 107.5, ScreenWidth - 128, 40);

[_verifyBtn setTitle:@"同意" forState:UIControlStateNormal];
        [_verifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        CAGradientLayer *gl = [CAGradientLayer layer];
        gl.frame = CGRectMake(0,0,ScreenWidth - 128,40);
        gl.startPoint = CGPointMake(0, 0.5);
        gl.endPoint = CGPointMake(1, 0.5);
        gl.colors = @[(__bridge id)[UIColor colorWithRed:28/255.0 green:193/255.0 blue:134/255.0 alpha:1.0].CGColor,(__bridge id)[UIColor colorWithRed:44/255.0 green:182/255.0 blue:63/255.0 alpha:1.0].CGColor];
        gl.locations = @[@(0),@(1.0f)];
        [_verifyBtn.layer addSublayer:gl];
        _verifyBtn.layer.cornerRadius = 20;
        _verifyBtn.layer.masksToBounds = YES;
        _verifyBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
        [_verifyBtn addTarget:self action:@selector(verifyBtnAction:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _verifyBtn;
}

上面的这种写法是可以实现按钮背景颜色的渐变的效果,但是会有问题,你会发现按钮上面的文字确不见了。为什么会出现这种问题,这个我们需要理解UIView与layer的区别。这个问题我就不在一一细说,请自行百度。正确的写法请看下面的代码:

-(UIButton *)verifyBtn{
    if (!_verifyBtn) {
        _verifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _verifyBtn.frame = CGRectMake(64, ScreenHeight - NaviBarHeight -TabbarHeight - 107.5, ScreenWidth - 128, 40);
        CAGradientLayer *gl = [CAGradientLayer layer];
        gl.frame = CGRectMake(0,0,ScreenWidth - 128,40);
        gl.startPoint = CGPointMake(0, 0.5);
        gl.endPoint = CGPointMake(1, 0.5);
        gl.colors = @[(__bridge id)[UIColor colorWithRed:28/255.0 green:193/255.0 blue:134/255.0 alpha:1.0].CGColor,(__bridge id)[UIColor colorWithRed:44/255.0 green:182/255.0 blue:63/255.0 alpha:1.0].CGColor];
        gl.locations = @[@(0),@(1.0f)];
        [_verifyBtn.layer addSublayer:gl];
        _verifyBtn.layer.cornerRadius = 20;
        _verifyBtn.layer.masksToBounds = YES;
        _verifyBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
        [_verifyBtn addTarget:self action:@selector(verifyBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [_verifyBtn setTitle:@"同意" forState:UIControlStateNormal];
        [_verifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    }
    return _verifyBtn;
}

 类似资料: