首页 > 解决方案 > 解决使用自定义 UITableViewCell 时没有自定义 init 方法的问题

问题描述

init设置自定义方法时如何解决无法使用自定义方法的问题UITableViewCell?我已经看到如何在 UITableViewCell 上使用自定义初始化程序?,但是,我正在添加我想在我的init方法中覆盖的约束。我需要添加一个格式不同的文本字段,例如数字。

我尝试从我的UITableViewCell类继承并在我的方法中设置样式枚举init,但在调用super.init.

class LabelIntegerTextfieldTableViewCell: LabelTextfieldTableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
    {
        super.textFieldStyle = .Integer
// 'self' used in property access 'textFieldStyle' before 'super.init' call

        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
open class LabelTextfieldTableViewCell: UITableViewCell
{
    public var label = UILabel()
    public var textField = UITextField()
    public var textFieldStyle = eTextfieldStyle.Integer

    override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        switch textFieldStyle
        {
        case .Integer:
            textField.contentVerticalAlignment = .center
            textField.textAlignment = .right
            textField.keyboardType = .numberPad
// snip

        if (textFieldStyle == .MediumText)
        {
            contentView.addConstraints(NSLayoutConstraint
              .constraints(withVisualFormat: 
              "H:|-[label]-[textField(==label)]-|", 
              options: [], metrics: nil, views: viewsDict))
        }
        else
        {
            contentView.addConstraints(NSLayoutConstraint
              .constraints(withVisualFormat: 
              "H:|-[label]-[textField(100)]-|", 
              options: [], metrics: nil, views: viewsDict))
        }

我知道在其他 SO 帖子中提到了使用update方法,但正如我所说,我宁愿不删除约束和其他部分。

标签: iosswiftuitableviewcocoa-touch

解决方案


您试图实现的行为实际上并不是一个好的设计,因为UITableViewCells 被重用了。所以你不应该依赖于在init方法中配置它们的外观。例如,您可以实例化一个单元格传递Integer样式,然后,如果您将单元格设置为具有不同的样式,您将有一个不一致的状态(因为您将看到的内容不会反映您设置的内容)。话虽如此,您应该考虑使用更具反应性的方法,您的单元格的行为根据设置的内容,无论何时设置。在你的情况下,你可能想看看didSet属性观察者。你会有类似下面的东西:

public var textFieldStyle = eTextfieldStyle.Integer {
  didSet {
    updateAppearance()
  }
}

func updateAppearance() {
  switch textFieldStyle {
    case .Integer:
      // ...
  }
}

编辑

而在你的tableView(_:cellForRowAt:)你只需要设置正确的样式,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "your cell identifier goes here", for: indexPath)

  // Here you obtain the proper style depending on the index path, for instance:
  if indexPath.row == 0 {
    cell.textFieldStyle = .Integer
  } else {
    cell.textFieldStyle = . MediumText
  }
  return cell
}

推荐阅读