【问题标题】:Search bar not working in Swift 4 IOS App搜索栏在 Swift 4 IOS 应用程序中不起作用
【发布时间】:2019-03-31 20:29:28
【问题描述】:

我已经实现了一个搜索栏来搜索用户,但是当我搜索某些内容时,表格视图中没有显示任何内容。我在下面附上了我的视图控制器的图片。

视图控制器:

此视图控制器显示所有用户的列表,搜索栏应该帮助用户找到用户名。

import UIKit

class FindFriendsViewController: UIViewController {

var users = [User]()

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var searchItem = [String]()
var searching = false

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.tableFooterView = UIView()
    tableView.rowHeight = 71

    let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
    tap.cancelsTouchesInView = false
    self.view.addGestureRecognizer(tap)
}

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

    UserService.usersExcludingCurrentUser { [unowned self] (users) in
        self.users = users

        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

}

extension FindFriendsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if searching {
        return searchItem.count
    } else {
        return users.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FindFriendsCell") as! FindFriendsCell

// 让 user = users[indexPath.row]

    var usernamesArr = [String]()
    for user in users {
        usernamesArr.append(user.username)
    }

    if searching {
        cell.textLabel?.text = searchItem[indexPath.row]
    } else {
        cell.textLabel?.text = usernamesArr[indexPath.row]
        cell.delegate = self
        configure(cell: cell, atIndexPath: indexPath)
    }

    return cell
}

func configure(cell: FindFriendsCell, atIndexPath indexPath: IndexPath) {
    let user = users[indexPath.row]

    cell.usernameLabel.text = user.username
    cell.followButton.isSelected = user.isFollowed
}

}

extension FindFriendsViewController: FindFriendsCellDelegate {
func didTapFollowButton(_ followButton: UIButton, on cell: FindFriendsCell) {
    guard let indexPath = tableView.indexPath(for: cell) else { return }

    followButton.isUserInteractionEnabled = false
    let followee = users[indexPath.row]

    FollowService.setIsFollowing(!followee.isFollowed, fromCurrentUserTo: followee) { (success) in
        defer {
            followButton.isUserInteractionEnabled = true
        }

        guard success else { return }

        followee.isFollowed = !followee.isFollowed
        self.tableView.reloadRows(at: [indexPath], with: .none)
    }
}

}

extension FindFriendsViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    var usernamesArr = [String]()
    for user in users {
        usernamesArr.append(user.username)
    }
    searchItem = usernamesArr.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
    searching = true
    tableView.reloadData()
}

}

【问题讨论】:

    标签: ios swift uisearchbar searchbar


    【解决方案1】:

    我正在考虑您的代码中可能出现的不同问题。您需要设置搜索栏委托和搜索结果更新器:

    yourSearchController.searchBar.delegate = self
    yourSearchController.searchResultsUpdater = self

    如果你没有控制器,而是直接搜索栏:

    yourSearchBar.delegate = self
    yourSearchBar.searchResultsUpdater = self

    这是你的代表:

    extension MasterViewController: UISearchBarDelegate {
      // MARK: - UISearchBar Delegate
      func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
      }
    }
    
    extension MasterViewController: UISearchResultsUpdating {
      // MARK: - UISearchResultsUpdating Delegate
      func updateSearchResults(for searchController: UISearchController) {
        let searchBar = searchController.searchBar
        let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
        filterContentForSearchText(searchController.searchBar.text!, scope: scope)
      }

    或者您可能缺少更新之类的东西。检查数据的路径排除问题之一的时间。首先,您在搜索栏中输入文本,然后检查文本所在的代码以及发生的情况。当搜索栏处于结束编辑状态时,您是否更新了表格视图?

    如果对您没有帮助,请查看我之前关注的这个精彩教程:Search Bar iOS

    【讨论】:

    • 谢谢!我会查看教程,看看你提供的代码是否有效。
    【解决方案2】:

    尝试使用此方法过滤搜索用户名

    searchItem = users.filter({ (objUser) -> Bool in
                    return (objUser.username?.lowercased() ?? "").starts(with: searchBar.text!.trim().lowercased())
                })
    

    希望这会对你有所帮助。

    【讨论】:

    • 嗨。它说“'String'类型的值没有成员'trim'”
    • 否,但值不是根据用户名中的字符串过滤的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多