UITableViewController初始化时未选择单元格

时间:2019-05-28 12:04:06

标签: ios swift uitableview uikit

我有UITableViewController的以下子类:

final public class ILoveAppleSelectorTableViewController: UITableViewController {
    public weak var delegate: ILoveAppleSelectorTableViewControllerDelegate?
    public var data = [ILoveAppleGroupModel]()

    convenience init() {
        self.init(style: .plain)
    }

    convenience init(data: [ILoveAppleGroupModel]) {
        self.init(style: .plain)
        self.data = data
    }

    override public func viewDidLoad() {
        super.viewDidLoad()
        title = "Select APple Product"
        tableView.registerCellClass(CheckmarkTableViewCell.self)
        tableView.allowsSelection = true
        tableView.allowsMultipleSelection = false
    }

    // MARK: - Selection

    public func selectItem(at indexPath: IndexPath) {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }

    // MARK: - Table view data source

    override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: CheckmarkTableViewCell = tableView.dequeueCell(for: indexPath)
        let item = data[indexPath.row]
        cell.textLabel?.text = item.material_group_name
        return cell
    }

    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedappleProduct = data[indexPath.row]
        delegate?.ILoveAppleSelector(controller: self, didSelect: selectedappleProduct)
    }
}

我创建它的一个实例并调用selectItem方法:

let data = Array(appleProducts)
let selector = AppleProductSelector(data: data)
selector.selectItem(at: IndexPath(indexes: [0, 0]))
navigationController?.pushViewController(selector, animated: true)

我在调试器中检查到selectItem方法已成功调用,但是未选择任何内容。

如果我在viewWillAppear上选择了一个项目,则一切正常,并且该项目显示为选中状态:

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    selectItem(at: selectedIndexPath)
}

1 个答案:

答案 0 :(得分:2)

默认情况下,显示表视图时,表视图控制器将清除选择。

您正在实例化您的类,然后“选择”一行,然后将VC推入堆栈。出现时,它将清除选择。

在IB /情节提要中,它由一个复选框控制:

enter image description here

(取消选中此框可防止选择被清除)

在代码中,您可以将其添加到您的init函数中(或也许在viewDidLoad()中):

self.clearsSelectionOnViewWillAppear = false