如何将子视图添加到tableView cell.contentView swift

时间:2015-03-27 19:50:08

标签: swift tableview cell subview

我有点困惑,我应该在哪里声明以及如何将subView添加到单元格以使单元格的宽度更短。

我试图在我的tableViewCell类中使用func viewWillLayoutSubviews(){}但是我无法从那里访问tableView ...很奇怪..

我需要为此工作提供哪些子类以及在何处插入此代码?

目前,此代码只是向单元格添加子视图,并在单元格顶部添加浮点数,而不是包含单元格。我在cellForRowAtIndexPath中使用它。

  let testFrame : CGRect = cell.contentView.frame
    var testView : UIView = UIView(frame: testFrame)
    testView.backgroundColor = UIColor.redColor()
    testView.alpha=0.5
    testView.bounds = CGRectMake(cell.bounds.origin.x,
        cell.bounds.origin.y,
        cell.bounds.size.width - 50,
        cell.bounds.size.height);
    //TableViewCell.addSubview(testView)
    cell.contentView.addSubview(testView)
    return cell

1 个答案:

答案 0 :(得分:1)

在单元格内添加子视图,您要添加testView作为单元格内容视图的视图。 testView的框架将相对于单元格的内容视图(testView的超级视图)。

更改UITableViewCell的宽度不是一个好主意,因为可能会出现意外的副作用。您可以覆盖从setFrame返回的UITableViewCell子类中的cellForRowAtIndexPath:。更多信息:How to set the width of a cell in a UITableView in grouped style

如果您需要不是全宽的单元格,或者让您的表格查看所需的宽度,您应该查看UICollectionView

相关问题