在UITableView下面设置背景图层?

时间:2013-09-05 14:16:51

标签: ios cocoa-touch

我正在关注渐变这个教程:

http://danielbeard.wordpress.com/2012/02/25/gradient-background-for-uiview-in-ios/

但我似乎无法在我的tableView下面插入子图层,因此插入图层:

CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];

为什么它会超越我的故事板tableView?

编辑:

我的桌子视图在那里,在图层下面,我可以点击它和一切,但我看不到它

3 个答案:

答案 0 :(得分:5)

以这种方式执行此操作的正确方法是渐变将保留在表视图后面而不是在tableView滚动时滚动是在tableView的backgroundView中设置渐变

如何在Swift 3中执行此操作

let gradientLayer = CAGradientLayer()
let bgView = UIView.init(frame: self.tableView.frame)
bgView.layer.insertSublayer(gradientLayer, at: 0)
self.tableView.backgroundView = bgView

答案 1 :(得分:1)

如果将它放在viewDidAppear中,它应该可以工作。但是,将大小设置为self.view.bounds只会使渐变位于屏幕的底部 - 滚动时,渐变将随之滚动。如果希望渐变与表视图一样长,则必须将其高度设置为contentSize的高度。您还需要设置单元格的背景颜色以清除以查看渐变(在tableView中:willDisplayCell:forIndexPath:)

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    CAGradientLayer *bgGradient = [CAGradientLayer layer];
    bgGradient.frame = CGRectMake(self.tableView.bounds.origin.x, self.tableView.bounds.origin.y, self.tableView.bounds.size.width, self.tableView.contentSize.height);
    bgGradient.colors = @[(id)[[UIColor colorWithRed:150/255.0 green:2150/255.0 blue:233/255.0 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:208/255.0 green:210/255.0 blue:216/255.0 alpha:1] CGColor]];
    bgGradient.locations = @[@0.02f,@1.00f];
    [bgGradient setMasksToBounds:YES];
    [self.view.layer insertSublayer:bgGradient atIndex:0];

}

此方法的一个问题是渐变的长度和外观将根据表视图中的行数而变化。如果希望渐变保持相同的长度,则可能需要将其添加到窗口中(并使表视图的背景颜色清晰)。

答案 2 :(得分:0)

对于面临此问题的任何人:

如果您使用的是UITableViewController,则需要在生命周期的后期设置自定义视图,例如viewDidLayoutSubviews 原因是在viewDidLoad tableView框架中尚未设置。

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    
    let backgroundView = UIView(frame: tableView.bounds)
    backgroundView.backgroundColor = .white
    backgroundView.layer.insertSublayer(bgLayer, at: 0)
    
    tableView.backgroundView = backgroundView
}