来自XIB的自定义UITableViewCell:contentView宽度始终相同

时间:2016-09-15 12:20:35

标签: ios swift uitableview xib

我已经使用$('.loadimgs').click(function(ev){ var gallery_id=$(this).attr("data-gallery"); $('.load_more_images').load("/more-images.php?gallery_id="+gallery_id); alert("It works" + gallery_id); }); 文件创建了自定义UITableViewCell。在那里,我已经放置了几个相对于xib宽度的标签和视图。不幸的是,无论选择哪个设备,contentView属性始终保持不变。

我的ViewController也是从nib加载的:

contentView.bounds.width

class ViewController: UIViewController { @IBOutlet var tableView: UITableView! init(title: String) { super.init(nibName: "ViewController", bundle: nil) } override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell") } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as! CustomTableViewCell return cell } } 类中,我打印出内容视图的width属性:

CustomTableViewCell

这总是打印出Interface Builder中设置的宽度,即使它应该遵循使用AutoLayout的 override func awakeFromNib() { super.awakeFromNib() print("self.contentView.bounds.width: \(self.contentView.bounds.width)") } 的宽度:

enter image description here

尝试在返回之前设置单元格的框架没有工作:

tableView

2 个答案:

答案 0 :(得分:1)

如果您使用autolayout,请计算width中的cellforrowAtindexpath,并获得适当的宽度。在您的单元格获得自动布局之前调用awakeFromNib,因此它的宽度与interface builder中设置的宽度相同。

如果您使用自动布局,那么第二件事就是设置frame没有任何意义。如果您想更改height or width,那么您应该outlet of your constraint (height or width),然后将constant更改为所需的值!

如果您只想改变身高,那么您可以使用heightForRowAtIndexPathif else一起玩,根据条件返回所需的身高!

答案 1 :(得分:0)

快速4 +

您可以使用以下代码,它将设置XIB单元格的框架,还可以借助XIB高度和宽度来调整内容。

let cellRect = CGRect(x: 0, y: 0, width: postTableView.frame.size.width, height: imageHeight)
cell?.frame = cellRect

希望它会起作用