gpt4 book ai didi

UIButton 上的 iOS 线性渐变无法正确显示

转载 作者:行者123 更新时间:2023-11-29 05:58:46 25 4
gpt4 key购买 nike

我正在尝试向自定义 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];

enter image description here

如果我在这一行中添加:

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

然后按钮看起来像这样。

enter image description here

最佳答案

在我分配框架后,您的代码可以正常工作,例如:

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

并添加到 View Controller 的 View 中,例如:

[self.view addSubview:button];

关于UIButton 上的 iOS 线性渐变无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com