我在IB中用标签创建了一个UIView:6。我在tableView中使用它。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
// create background view
var backgroundView = cell.contentView.viewWithTag(6) as UIView!
backgroundView.layer.cornerRadius = 10
backgroundView.layer.masksToBounds = true
// create gradient layer
let gradient : CAGradientLayer = CAGradientLayer()
// create color array
let arrayColors: [AnyObject] = [
UIColor (red: 33/255, green: 33/255, blue: 39/255, alpha: 1).CGColor,
UIColor (red: 24/255, green: 24/255, blue: 28/255, alpha: 1).CGColor]
// set gradient frame bounds to match view bounds
gradient.frame = backgroundView.bounds
// set gradient's color array
gradient.colors = arrayColors
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.locations = [0.1, 0.9]
gradient.endPoint = CGPoint(x: 1, y: 1)
// replace base layer with gradient layer
backgroundView.layer.insertSublayer(gradient, atIndex: 0)
问题是,当backgroundView调整为Autolayout时,渐变层不会像我期望的那样:
gradient.frame = backgroundView.bounds
我在TableView单元格中找不到适用于UIViews的任何答案。
问题:强制应用于TableView中的UIView的图层使用autolayout调整大小的正确代码是什么?
答案 0 :(得分:0)
我认为您可以尝试将UITableViewCell子类化,然后将CAGradientLayer作为其默认层。
然后它的大小应该遵循它的等效视图,尽管我没有测试它。
答案 1 :(得分:0)
这是您正在寻找的答案:https://stackoverflow.com/a/4111917/2831015
UIView子类并将其用作" backgroundView"。通过将图层类重写为CAGradientLayer,您不需要将渐变添加为子图层,并且您的渐变将基于父图层自动调整大小。