繁体   English   中英

iOS如何获取TableView单元格中整个行的宽度

[英]iOS how to get the width of entire row in tableview cell

我正在尝试将单元格的左半部分设置为绿色,将单元格的右半部分设置为红色。 在注释cell.frame.width之前,请在此处检查我已完成的代码段以及得到的结果。 我们可以注意到有一些空白。 我的猜测是cell.frame没有给我正确的帧。

可以实现相同结果的任何帮助或其他方法,将不胜感激!

更新:表视图和约束这里

更好地使用自动布局,它将使应用程序可以在两个方向上工作。

而且在您的实现中,每次为每个单元格调用cellForRowAtIndexPath方法时,都会创建bgView,因此与仅创建bgView相比,更好地检查bgView是否为nil。 请参考下面的代码。

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

}

这样做可能有多种原因。 您可以尝试以下几种方法:

单元格可能为附件视图(例如复选标记,箭头等)留出空间。尝试将单元格的附件类型设置为.None:

cell.accessoryType = .None

与其在右侧添加视图,不如尝试设置单元格的背景色,然后将左侧设置为view.width / 2

cell.backgroundColor = UIColor.redColor
let leftViewFrame = cell.bounds
leftViewFrame.width = view.frame.width / 2.0
let leftView = UIView(frame: leftViewFrame)

另一个潜在的问题可以在viewDidLoad中解决:

self.automaticallyAdjustsScrollViewInsets = false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM