Как добавить границу в пользовательский UITableViewCell в ViewWillAppear - PullRequest
0 голосов
/ 10 октября 2019

У меня есть 2 табличных представления с настраиваемыми ячейками табличного представления, где выбор ячейки в первом табличном представлении переходит ко второму. Я пытаюсь добиться того, чтобы при выборе ячейки на втором экране добавлялась красная рамка, а если вы вернетесь к первому виду и вернетесь ко второму, у ячейки все еще будет граница.

Перед использованием пользовательских ячеек табличного представления я проверил на 2 контроллерах табличного представления, и код работал;однако это не относится к настраиваемым ячейкам табличного представления.

Вот код, который я использовал для контроллеров табличного представления (secondCategory - это класс, содержащий путь индекса выбранной ячейки):

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath)
    cell?.selectionStyle = UITableViewCell.SelectionStyle.none
    cell?.layer.borderWidth = 3.0
    cell?.layer.borderColor = UIColor.red.cgColor
    secondCategory.currentSelection = indexPath

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    if  secondCategory.currentSelection != nil {
        let cell = tableView.cellForRow(at: secondCategory.currentSelection!)
        cell!.selectionStyle = UITableViewCell.SelectionStyle.none
        cell!.layer.borderWidth = 3.0
        cell!.layer.borderColor = UIColor.red.cgColor
    }
}

Ниже приведен код для пользовательских ячеек табличного представления (в viewWillAppear я использую tableView (tableView: UITableView, cellForRowAt: IndexPath), потому что tableView.cellForRow (at: IndexPath) возвращает ноль):

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath)
    cell?.selectionStyle = UITableViewCell.SelectionStyle.none
    cell?.layer.borderWidth = 3.0
    cell?.layer.borderColor = UIColor.red.cgColor
    secondCategory.currentSelection = indexPath
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    if secondCategory.currentSelection != nil {
        let currentCell = tableView(secondTable, cellForRowAt: secondCategory.currentSelection!)
        currentCell.selectionStyle = UITableViewCell.SelectionStyle.none
        currentCell.layer.borderWidth = 3.0
        currentCell.layer.borderColor = UIColor.red.cgColor
    }
}

Может кто-нибудь сказать мне, почему код для пользовательских ячеек табличного представления не работает?

Ответы [ 2 ]

0 голосов
/ 10 октября 2019

Вы должны добавить свойства IBInspectables в свое расширение UIView, чтобы избежать наличия нежелательного кода в вашем контроллере или файле просмотра и установки границы непосредственно через xib или раскадровку.

Вот код.

    @IBInspectable
    var borderWidth: CGFloat {

        get {
            return layer.borderWidth
        }

        set {
            layer.borderWidth = newValue
        }
    }

    @IBInspectable
    var borderColor: UIColor? {

        get {

            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            return nil
        }

        set {

            if let color = newValue {
                layer.borderColor = color.cgColor

            } else {
                layer.borderColor = nil
            }
        }
    }

и будет показано так:

enter image description here

Более того, вы также можете получить доступ к этим свойствам в быстром коде со ссылкой на представление.

0 голосов
/ 10 октября 2019

Попробуйте переместить вашу логику в cellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

  let cell = tableView.dequeueReusableCell(withIdentifier: "IDENTIFIER", for: indexPath) as! CustomTableViewCell

  // TODO: Cell logic

  // Border logic
  if  secondCategory.currentSelection != nil {
    cell.selectionStyle = UITableViewCell.SelectionStyle.none
    cell.layer.borderWidth = 3.0
    cell.layer.borderColor = UIColor.red.cgColor
  }

  return cell
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...