ios - UIButton 上的 iOS 线性渐变无法正确显示
问题描述
我正在尝试向我的自定义 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];
然后按钮看起来像这样。
解决方案
您的代码在我分配后工作正常frame
,例如:
button.frame = CGRectMake(50, 50, 100, 40);
并添加到视图控制器的视图中,例如:
[self.view addSubview:button];
推荐阅读
- wordpress - 安装谷歌翻译后页面部分网址不起作用
- php - 如何获得仅活跃的学生总数
- c++ - 由于 HID 句柄无效(Windows HID C++ API),HidD_* 函数全部失败
- sql - InfluxQL:名为 Group 的标签导致悲伤
- circleci - CircleCI - 基于 ENV 变量的条件
- r - 在cowplot中调整和定位ggplots
- java - 我构建了包含第三方库的库,我想从应用程序中使用该第三方库
- openlayers-6 - 使用多个标记居中和缩小视图
- java - 由于错误无法加载插件:“Jar 不包含 plugin.yml”
- sql - 使用连接查询进行聚合的技巧