【问题标题】:iOS linear gradient on UIButton not displaying properlyUIButton 上的 iOS 线性渐变无法正确显示
【发布时间】:2019-07-19 10:59:06
【问题描述】:

我正在尝试向我的自定义 UIButton 添加渐变,但是当我运行它时,按钮显示为透明而不是显示所需的渐变。

这是我的代码:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.titleLabel.font = [UIFont fontWithName:@"SFUIDisplay-Medium" size:16];
[button setTitleColor:[UIColor whiteColor]
             forState:UIControlStateNormal];
button.layer.cornerRadius = [UIButton cornerRadius];
button.contentEdgeInsets = UIEdgeInsetsMake(13, 0, 13, 0);

button.frame = CGRectMake(50, 50, 100, 40); //this line is new

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = button.layer.bounds;
gradientLayer.colors = [NSArray arrayWithObjects:
                        (id)[UIColor lightGrayColor].CGColor,
                        (id)[UIColor blackColor].CGColor,
                        nil];
gradientLayer.locations = [NSArray arrayWithObjects:
                           [NSNumber numberWithFloat:0.0f],
                           [NSNumber numberWithFloat:1.0f],
                           nil];
gradientLayer.cornerRadius = button.layer.cornerRadius;

gradientLayer.startPoint = CGPointMake(0, 0.5); //this line is new
gradientLayer.endPoint = CGPointMake(1, 0.5); //this line is new

[button.layer addSublayer:gradientLayer];
button.translatesAutoresizingMaskIntoConstraints = NO;
[button setTitle:@"Test"
        forState:UIControlStateNormal];
[button constrainHeight:56];
[button addTarget:self
        action:@selector(doAction)
        forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];

如果我在这一行添加:

button.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];

然后按钮看起来像这样。

【问题讨论】:

    标签: ios objective-c uibutton gradient


    【解决方案1】:

    在我分配frame 后,您的代码运行良好,例如:

    button.frame = CGRectMake(50, 50, 100, 40);
    

    并添加到视图控制器的视图中,例如:

    [self.view addSubview:button];
    

    【讨论】:

      【解决方案2】:

      首先,尝试将您的按钮添加到视图中。然后,看起来您并没有设置起点和终点。对于线性渐变,请尝试以下操作:

      [self.view addSubview: button];
      
      gradientLayer.startPoint = CGPointMake(x: 0, y: 0.5);
      gradientLayer.endPoint = CGPointMake(x: 1, y: 0.5);
      

      此配置将确保渐变从左侧中间开始,在右侧中间结束。您可以使用以下描述的想法修改不同类型渐变的值:

      (0, 0)     ||     (1, 0)
                 ||
      =========================
                 ||
      (1, 0)     ||     (1, 1)
      

      【讨论】:

        猜你喜欢
        • 2020-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-21
        • 2022-08-16
        • 2013-02-26
        • 1970-01-01
        相关资源
        最近更新 更多