Панель поиска не обновляет цвет UIbutton - PullRequest
0 голосов
/ 30 марта 2020

Вот моя головная боль ... Надеюсь, у кого-то есть лекарство.

Ситуация - у меня есть панель поиска, связанная с табличным представлением чуть ниже - Ячейка табличного представления состоит из 1 метки и 1 кнопки - Кнопка «избранная» кнопка, связанная с coredata - если текст метки существует в coredata, его цвет коричневый - если текст не существует в coredata, его цвет серый. Если его нажать, он станет коричневым, и текст метки будет зарегистрирован в coredata

Головная боль - все отлично работает для первой фильтрации (все на месте, цвета кнопок отображаются правильно, если текст регистрируется, но нет, и регистрация, нажав на кнопку, работает отлично, НО ... - когда поиск изменяется, ячейки фильтруются (не) отлично, но не кнопка: те, кто должен появиться внутри, отображаются коричневым цветом - Если я меняю экран и возвращаюсь, все сбрасывается, и цвета кнопок в порядке.

Я не могу узнать, как обновить sh цвет заголовка кнопки во время поиска. Название кнопки - текст. Любая подсказка?

Код в CellForRowAt

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

    let cell = searchTbv.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath) as! SearchTbvCell

    if searhing {
        cell.searchLbl.text = mySearch[indexPath.row]
    }
    else {
        cell.searchLbl.text = dataSearch.searchItem[indexPath.row]
    }

    return cell
}

Код для строки поиска

extension SearchVC: UISearchBarDelegate {

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    searhing = true

    mySearch = dataSearch.searchItem.filter({$0.lowercased().folding(options: .diacriticInsensitive, locale: .current).prefix(searchText.count) == searchText.lowercased()})

    searchTbv.reloadData()

}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searhing = false
    searchBar.text = ""
    searchTbv.reloadData()

}

Код для установки цвета кнопки (код находится в пользовательском классе ячеек):

class SearchTbvCell: UITableViewCell {

//MARK: OUTLETS
@IBOutlet weak var searchLbl: UILabel!
@IBOutlet weak var searchBtn: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()
    fetchFromCoreData()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    fetchFromCoreData()
}


@IBAction func favoriteBtnTapped(_ sender: UIButton) {

    // Set fav button color to brown if selected/tapped
    searchBtn.setTitleColor(.brown, for: .normal)

    // Permanently record selection as favorite into coredata
    recordPermanently()
}



//MARK: METHODS

// Fetch contents from CoreData and up-date button's color consequently
func fetchFromCoreData () {
    // Create a reference to container
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    // Create a context from the container
    let managedContext = appDelegate?.persistentContainer.viewContext
    // Prepare a request and sorting
    let myRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "MyFavorites")
    myRequest.predicate = NSPredicate(format:"favoriteWines = %@", searchLbl.text!)
    do {
        let results = (try managedContext?.fetch(myRequest))!
        for _ in results {
            searchBtn.setTitleColor(.brown, for: .normal)
        }
    }
    catch{}
}


// Record permanently in core data and changethe button's color
func recordPermanently(){
    // Create a reference to container
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
    // Create a context from the container
    let managedContext = appDelegate.persistentContainer.viewContext
    // Create an entity to manage records
    let recordEntity = NSEntityDescription.entity(forEntityName: "MyFavorites", in: managedContext)!
    // Create a new record
    let newRecord = NSManagedObject(entity: recordEntity, insertInto: managedContext)
    // Pass values to new record
    newRecord.setValue(searchLbl.text!, forKeyPath: "favoriteWines")
    // Save record
    do {
        try managedContext.save()
        searchBtn.setTitleColor(.brown, for: .normal)
    }
    catch let error as NSError{
        print("Failed to save permanently. \(error), \(error.userInfo)" )
    }
}

}

Ответы [ 2 ]

0 голосов
/ 04 апреля 2020

Я мог бы наконец-то решить эту проблему, просто добавив cell.searchBtn.setTitleColor (.lightGray, for: .normal) в код cellForRowAt (как показано ниже).

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

    let cell = searchTbv.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath) as! SearchTbvCell

    if searhing {
        cell.searchLbl.text = mySearch[indexPath.row]
        cell.searchBtn.setTitleColor(.lightGray, for: .normal) // This line has fixed the problem

        if cell.searchLbl.text == myProperties.isInCoreData {
            cell.searchBtn.setTitleColor(.brown, for: .normal)
        }
        else {
            cell.searchBtn.setTitleColor(.lightGray, for: .normal)
        }
    }
    else {
        cell.searchLbl.text = dataSearch.searchItem[indexPath.row]
        cell.searchBtn.setTitleColor(.lightGray, for: .normal) // This line has fixed the problem
    }

    return cell
}
0 голосов
/ 30 марта 2020

Отказ от ответственности: набрано в браузере, не проверено в Xcode

Вы не указали, где и как вы устанавливаете цвет кнопки, но я рекомендую вам сделать это в willDisplayCell:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell,  forRowAt indexPath: IndexPath) {
    if cell.label.text.existsInCoreCata() {
         cell.button.setTitleColor(.brown, for: .normal)
    }
    else {
        cell.button.setTitleColor(.grey, for: .normal)
    }
}

existsInCoreCata() - это ваш код, в котором вы проверяете, существует ли метка в CoreData.

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