我正在尝试将单元格的左半部分着色为绿色,将单元格的右半部分着色为红色。在评论 cell.frame.width
之前,请检查代码片段 HERE我已经完成并得到了结果。我们可以注意到尾随有一些空白。我的猜测是 cell.frame
没有给我所需的正确框架。
非常感谢任何可以达到相同结果的帮助或其他方法!
更新: TableView 和约束 Here
最佳答案
最好使用自动布局,这将使应用程序在两个方向上都能工作。
而且在您的实现中,每次为每个单元格调用 cellForRowAtIndexPath 方法时都会创建 bgView,因此最好检查 bgView 是否为 nil 而不是仅创建 bgView。 请引用以下代码。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellID", forIndexPath: indexPath)
cell.backgroundColor = UIColor.clearColor()
if cell.backgroundView == nil {
let leftView = UIView()
let rightView = UIView()
rightView.backgroundColor = UIColor.redColor()
leftView.backgroundColor = UIColor.yellowColor()
cell.backgroundView = UIView()
cell.backgroundView?.addSubview(leftView)
cell.backgroundView?.addSubview(rightView)
leftView.translatesAutoresizingMaskIntoConstraints = false;
rightView.translatesAutoresizingMaskIntoConstraints = false;
let viewDict = ["leftView":leftView, "rightView":rightView]
cell.backgroundView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[leftView]-0-|", options: [], metrics: nil, views: viewDict))
cell.backgroundView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rightView]-0-|", options: [], metrics: nil, views: viewDict))
cell.backgroundView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[leftView]-0-[rightView(==leftView)]-0-|", options: [], metrics: nil, views: viewDict))
}
cell.textLabel?.text = "dsfsdkjfh fkjhsdkjfhs kdfksdhfk sdf";
return cell
}
关于iOS如何获取tableview单元格中整行的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213783/