【问题标题】:TableView displaying cells uncorrectlyTableView 显示单元格不正确
【发布时间】:2025-11-30 11:55:02
【问题描述】:

拥有房产

var resultSearchController = UISearchController()

在 viewDidLoad() 方法上创建 UISearchController

        self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()
        controller.searchBar.barStyle = UIBarStyle.black
        controller.searchBar.barTintColor = UIColor.white
        controller.searchBar.backgroundColor = UIColor.clear
        controller.hidesNavigationBarDuringPresentation = false
        self.tableView.tableHeaderView = controller.searchBar
        return controller
    })()

结果有一个正常显示的注释文本加号,特别是在每个单元格的左上角显示文本的开头。 我能做错什么吗? 附言发现它很可能与 UISearchBar 无关

【问题讨论】:

    标签: ios uitableview swift3 uisearchdisplaycontroller


    【解决方案1】:

    我不熟悉您如何创建 resultSearchController,因为我从未见过这样的构造。但是,这可能是我的有限知识。我会稍微不同地创建 resultSearchController 以获得更可能成功的结果。

    lazy var resultSearchController : UISearchController = {
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()
            controller.searchBar.barStyle = UIBarStyle.black
            controller.searchBar.barTintColor = UIColor.white
            controller.searchBar.backgroundColor = UIColor.clear
            controller.hidesNavigationBarDuringPresentation = false
            self.tableView.tableHeaderView = controller.searchBar
            return controller
    }()
    

    这是延迟初始化将在使用时创建的变量并获取您定义的所有设置的正确方法。

    如果这不起作用,则问题不是定义和初始化,您应该显示更多可能出错的代码。

    【讨论】:

    • 此建议
    【解决方案2】:

    我发现我犯了错误。我使用属性cell.textLabel 而不是cell.noteLabel。你的时间。

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "NoteTableViewCell"
    
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! NoteTableViewCell
        let note: Note
        if self.resultSearchController.isActive {
            note = filteredNotes[indexPath.row]
            cell.textLabel?.text = filteredNotes[indexPath.row].note
        } else {
            note = notes[indexPath.row]
            cell.textLabel?.text = notes[indexPath.row].note
        }
    
        return cell
    }
    

    【讨论】:

    • 没问题。祝你好运。
    最近更新 更多