UITableViewCell - 根据内容选择背景大小

Mar*_*rry 0 uitableview ios swift

我有这个代码来获取表格单元格

func getCell(_ tableView: UITableView) -> UITableViewCell? {
     var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: CELL_REUSE_ID)

     if (cell == nil)
     {
        //init and configure the cell
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: CELL_REUSE_ID)

        let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
        selectedView.backgroundColor = UIColor.black.withAlphaComponent(0.3)

        let layer = selectedView.layer
        layer.borderColor = UIColor.blue.cgColor
        layer.borderWidth = getCellBorderWidth();
        layer.cornerRadius = getCellCornerRadius();
        layer.backgroundColor = UIColor.blue.cgColor

        cell!.selectedBackgroundView = selectedView
     }

     return cell
 }


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell:UITableViewCell? = getCell(tableView)

        cell!.backgroundColor = UIColor.clear

        cell!.textLabel!.textColor = UIColor.darkText
        cell!.textLabel!.text = tableData[indexPath.row]
        cell!.textLabel!.textAlignment = .right
        cell!.textLabel!.numberOfLines = 1
        cell!.textLabel!.adjustsFontSizeToFitWidth = true

        return cell!
    }
Run Code Online (Sandbox Code Playgroud)

单元格和表格是在代码中生成的,没有 xib。现在,如果我选择单元格,背景将覆盖表格的整个宽度。如何为某些单元格设置背景,即表格宽度的一半(或其他百分比)?

Cod*_*eal 5

我想你可以添加另一个视图selectedBackgroundView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        // selectedBackgroundView
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor(white: 0, alpha: 0)
        // add another view to selectedBackgroundView, and set any frame for this view
        let selectView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        selectView.backgroundColor = .red
        backgroundView.addSubview(selectView)
        cell?.selectedBackgroundView = backgroundView
    }

    return cell!

}
Run Code Online (Sandbox Code Playgroud)