UIView背景梯度与接口生成器视图

Mic*_*ton 8 ios ios6

我想使用渐变作为UIView的背景.我知道这通常是用图像和backgroundColor属性完成的.但是,我想学习如何在代码中执行此操作.使用/sf/answers/135204891/我可以以UIView编程方式创建并为其提供渐变层.这非常有效.

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 340, 280, 100)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor], (id)[[UIColor yellowColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:view];
Run Code Online (Sandbox Code Playgroud)

但是,如果我在Interface Builder中放置一个视图(背景设置为clear)并尝试相同的事情,渐变永远不会出现.

CAGradientLayer *gradient2 = [CAGradientLayer layer];
gradient2.frame = self.containerView.bounds;
gradient2.colors = [NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor], (id)[[UIColor greenColor] CGColor], nil];
[self.containerView.layer insertSublayer:gradient2 atIndex:0];
Run Code Online (Sandbox Code Playgroud)

我还需要在IB或代码中做些什么来使这项工作成功吗?

小智 3

我遇到了同样的问题,但最终发现 UIView 尚未在您尝试设置背景渐变的代码中创建,我猜在您的情况下可能是以下之一 - viewDidLoad或 - viewWillAppear因此

self.containerView.bounds 将为 {{0, 0}, {0, 0}}

相反,你应该在里面设置渐变层

查看是否出现

此时视图已创建。