8

我想使用渐变作为 UIView 的背景。我知道这通常是通过图像和backgroundColor属性完成的。但是,我想学习如何在代码中做到这一点。使用https://stackoverflow.com/a/1931498/99683我可以以编程方式创建一个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];

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

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];

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

4

2 回答 2

3

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

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

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

viewDidAppear

此时视图已创建。

于 2013-08-01T16:09:28.397 回答
1

该库支持使用 IB_DESIGNABLE / IBInspectable 在 Storyboard 中设置渐变背景。

这真的很有用。

https://github.com/recruit-mtl/EXTView/

于 2016-03-08T06:28:49.217 回答