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

标签 ios swift uitableview

我正在尝试将单元格的左半部分着色为绿色,将单元格的右半部分着色为红色。在评论 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/

相关文章:

ios - 子类化 UIView 时如何检测箭头键?

iphone - 如何增加UITableView分隔符高度?

ios - 从复杂的 ScrollView 页面移动时崩溃

ios - 如何强制 UICollectionView 滚动到特定行并加载该行的单元格,同时隐藏 Collection View ?

ios - 你如何在一个屏幕上有两个随机单词生成器

iOS - scrollView 和 setContentSize

ios - 访问电话簿 ios 时应用程序崩溃

iphone - 将数据发布到 http iPhone

ios - 将 Objective-C 属性显式导入 Swift 作为可选值

php - Swift 3 上传图像到 PHP 失败