如何将子视图添加到 tableView cell.contentView swift
how to add a subview to a tableView cell.contentView swift
我有点困惑我应该在哪里声明以及如何将子视图添加到单元格以使单元格的宽度更短。
我尝试在我的 tableViewCell 中使用 func viewWillLayoutSubviews(){} class 但我无法从那里访问 tableView...很奇怪..
我需要 subclass 什么才能让它工作,我需要在哪里插入这段代码?
目前这段代码只是向单元格添加一个子视图,并且有点浮动在单元格的顶部而不是包含单元格。我在 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
在单元格内添加了一个子视图,您正在添加 testView
作为单元格内容视图的 sub 视图。 testView
的框架将相对于单元格的内容视图(testView
的父视图)。
更改 UITableViewCell
的宽度不是一个好主意,因为可能会产生意想不到的副作用。您可以在 UITableViewCell
的子类中覆盖 setFrame
,您从 cellForRowAtIndexPath:
中 return。更多信息在这里:How to set the width of a cell in a UITableView in grouped style
如果您需要非全宽的单元格或使 table 查看您需要的宽度,您应该查看 UICollectionView
。
我有点困惑我应该在哪里声明以及如何将子视图添加到单元格以使单元格的宽度更短。
我尝试在我的 tableViewCell 中使用 func viewWillLayoutSubviews(){} class 但我无法从那里访问 tableView...很奇怪..
我需要 subclass 什么才能让它工作,我需要在哪里插入这段代码?
目前这段代码只是向单元格添加一个子视图,并且有点浮动在单元格的顶部而不是包含单元格。我在 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
在单元格内添加了一个子视图,您正在添加 testView
作为单元格内容视图的 sub 视图。 testView
的框架将相对于单元格的内容视图(testView
的父视图)。
更改 UITableViewCell
的宽度不是一个好主意,因为可能会产生意想不到的副作用。您可以在 UITableViewCell
的子类中覆盖 setFrame
,您从 cellForRowAtIndexPath:
中 return。更多信息在这里:How to set the width of a cell in a UITableView in grouped style
如果您需要非全宽的单元格或使 table 查看您需要的宽度,您应该查看 UICollectionView
。