【问题标题】:draw a colored circle in a UITableViewCell在 UITableViewCell 中绘制一个彩色圆圈
【发布时间】:2016-09-16 15:47:29
【问题描述】:

我正在尝试生成一个左侧带有彩色圆圈的 UITableViewCell。 我的计划是使用 UIButton 并操纵其图层的角半径。 但是,彩色按钮永远不会出现。

我的xib:

我的 ColorHolder UIButton 有一个 IBOutlet,它的颜色有一个变量。

class ColoredCircleCell: UITableViewCell {

    @IBOutlet weak var colorHolder: UIButton!
    @IBOutlet weak var infoRow1: UILabel!
    @IBOutlet weak var infoRow2: UILabel!

    var circleColor: CGColor = UIColor.clear.cgColor 

    override func awakeFromNib() {
        super.awakeFromNib()

        colorHolder.layer.cornerRadius = colorHolder.bounds.size.height / 2
        colorHolder.layer.backgroundColor = circleColor
        colorHolder.clipsToBounds = true
}

在我的 cellForRowAt 索引路径中:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CircleCell", for: indexPath) as! ColoredCircleCell

        print(cell.colorHolder.bounds.size.height)

        cell.colorHolder.layer.cornerRadius = cell.colorHolder.bounds.size.height / 2
        cell.colorHolder.layer.backgroundColor = UIColor.red.cgColor

        cell.infoRow1.text = "H1"

        return cell
    }

控制台告诉我单元格的大小是 1000。我猜它仍然没有根据行高调整大小。

编辑:我已将问题范围缩小到 cell.colorHolder.layer.cornerRadius = cell.colorHolder.bounds.size.height / 2 。 cell.colorHolder.bounds.size.height 的值始终为 1000。如何在将其呈现到屏幕后提取正确的值?

输出:

如何为我的 UITableViewCell 添加一个可配置的圆圈?

【问题讨论】:

  • 检查可能有问题的按钮约束。
  • 按钮的大小是动态的吗?你不能硬编码cornerRadius吗?
  • 是的,目的是使按钮的大小动态化。不过,硬编码的cornerRadius 肯定会让我的生活更轻松

标签: ios swift uitableview


【解决方案1】:

我认为你设置的 colorbutton 约束就像 topspace 到 superview,bottomspace 到 superView。

如果是这种情况,则将底部空间删除到 superView 并添加高度约束。

比这样做

cell.colorHolder.layer.cornerRadius = cell.colorHolder.bounds.size.height / 2
cell.colorHolder.clipToBounds = true

它应该显示为圆形。

希望这能解决您的问题

【讨论】:

    【解决方案2】:

    只需覆盖layoutSubviews 并在那里设置您的拐角半径。

    - (void)layoutSubviews {
       [super layoutSubviews];
       self.colorHolder.layer.cornerRadius = self.colorHolder.bounds.size.height / 2;
    }
    

    【讨论】:

    • 试过了,也遇到了同样的问题。我在cornerRadius print("the height: (colorHolder.bounds.size.height)") 的行上方添加了一个 println 语句。我一直在变身高:1000。不过还是谢谢你的建议
    • 你也可以在同一个地方检查单元格的大小吗?
    • 当然。它返回 89.95
    【解决方案3】:

    为了完成起见,在此处发布答案。 在访问边界之前,我必须添加 self.layoutIfNeeded()。 这个post帮助了我。

    override func awakeFromNib() {
            super.awakeFromNib()
    
            self.layoutIfNeeded()   
    
            colorHolder.layer.cornerRadius = colorHolder.bounds.size.height / 2
            colorHolder.layer.backgroundColor = circleColor
            colorHolder.clipsToBounds = true
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      相关资源
      最近更新 更多