【问题标题】:How to set a label in a cell of tableview by code?如何通过代码在tableview的单元格中设置标签?
【发布时间】:2017-08-01 02:26:15
【问题描述】:

如果我只是想通过代码设置标签,我应该这样写,

let label = UILabel()
label.frame = CGRect(x:10, y:   10, width:160, height:30)
label.text = "Test"
self.view.addSubview(label)

但是如果我想在tableView的一个单元格中设置一个标签,我该如何设置呢?

谢谢!

【问题讨论】:

    标签: ios xcode uitableview swift3


    【解决方案1】:

    您应该为您的单元格创建一个自定义类。这会为单元格添加标签,并使用锚定系统在标签上设置约束以填充整个单元格。

    class CustomCell: UITableViewCell {
    let label: UILabel = {
     let n = UILabel()
         n.textColor = UIColor.darkGray
         n.textAlignment = .center
         n.text = "Testing 123"
         n.font = UIFont(name: "Montserrat", size: 30)
     return n
    }()
    
     override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    
        addSubview(label)
    
       label.translatesAutoresizingMaskIntoConstraints = false
       label.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
       label.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
       label.topAnchor.constraint(equalTo: topAnchor).isActive = true
       label.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    }
    

    对于使用此自定义单元格的 ViewController,您必须像这样添加以下单元格注册,除非您使用的是故事板/界面构建器。

    class ControllerUsesCell: UITableViewController {
      let defaultCellId = "cellId"
    
      override func viewDidLoad() {
       super.viewDidLoad()
    
        tableView?.register(CustomCell.self, forCellWithReuseIdentifier: defaultCellId)
       }
    
      }
    

    【讨论】:

      【解决方案2】:

      UITableviewCell 子类有你可以使用的 textlabel 属性

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
         cell.textLabel?.text = "My Text"
         return cell
      }
      

      或者您也可以使用自定义单元格进行更多控制

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
          let label = UILabel()
          label.frame = CGRect(x: 10, y: 10, width: 160, height: 30)
          label.text = "Test"
          cell.contentView.addSubview(label)
          return cell
      }
      

      【讨论】:

      • 由于您在这里使用可重复使用的单元格,这是一个非常糟糕的解决方案;每次单元格出列时,您的代码都会添加一个 UILabel 。更好的解决方案是使用带有 UILabel 的自定义 UITableViewCell,无论是在情节提要、xib 文件中,还是以编程方式设置一次。
      • 我的错,用默认的 tableview 子类编辑了代码
      • 您的自定义单元实现仍然有同样的问题。
      猜你喜欢
      • 1970-01-01
      • 2021-11-28
      • 2011-09-16
      • 1970-01-01
      • 2020-07-06
      • 2021-01-16
      • 2017-05-09
      • 1970-01-01
      • 2020-03-14
      相关资源
      最近更新 更多