#ios #swift #uitableview
Вопрос:
Я застрял с проблемой, где у меня есть UITableView
метка и кнопка в каждой строке при нажатии на кнопку из конкретной строки он будет перемещаться к следующему виду, и это UITableView
со страной, список, при выборе страны он появится на предыдущий вид, и я хочу, чтобы обновить название страны с выбранной строки, может кто-нибудь руководство мне, как обновить его. Ниже приведен мой код. ТИА
FirstViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableCell
let dict = customData[indexPath.row] as? NSObject
cell.lblTitle.text = "Title"
// cell.lblSubTitle.text = ""
cell.selectedButton.tag = indexPath.row
cell.selectedButton.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
return cell
}
@objc func buttonClick(sender: UIButton){
let customCell = CountryViewController(nibName: nil, bundle: nil)
self.navigationController?.pushViewController(customCell, animated: true)
}
CountryViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CountryCell", for: indexPath) as! CountryTableCell
cell.lblTitle.text = CountryList[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCountry = CountryList[indexPath.row]
self.navigationController?.popViewController(animated: true)
}
Комментарии:
1. Обновите пользовательские данные с выбранным именем страны и перезагрузите представление таблицы. Можете ли вы объяснить, где вы хотите отобразить название страны после выбора?
2. если мы выберем 5-ю строку из FirstViewController, и она перенаправится на CountryViewController, а выбранная строка названия страны должна обновиться до 5-й строки в FirstViewController
Ответ №1:
Вы можете использовать шаблон делегирования:
protocol SelectCountry {
func countrySelected(withName countryName: String)
}
в вашем FirstViewController.swift соответствует этому протоколу
extension FirstViewController: SelectCountry {
func countrySelected(withName countryName: String) {
// Assign country name to your label here
}
в вашем CountryViewController.swift создайте переменную с именем делегат/любое имя, которое вы хотите
var delegate: SelectCountry?
в вашем методе нажатия кнопки
customCell.delegate = self
в вашем CountryViewController в методе didSelectRowAt
delegate?.countrySelected(withName: CountryList[indexPath.row])
ваша метка будет обновлена с указанием названия страны, выбранного вами в CountryViewController.
ПРИМЕЧАНИЕ: Имена-это просто заполнители, здесь вы можете использовать свои собственные имена для протокола/методов
Комментарии:
1. как назначить метку для определенной строки таблицы. пример, если мы хотим обновить метку 5-й строки.
2. если мы выберем 5-ю строку из FirstViewController, и она перенаправится на CountryViewController, а выбранная строка названия страны должна обновиться до 5-й строки в FirstViewController
3. @RakshitKumar Вижу, что вы устанавливаете тег на кнопку в FirstViewController.swift. Вам просто нужно получить тег в методах @objc, таких как
index = sender.tag
. когда ваша функция делегирования запускается, вы можете выполнить выборкуcustomData[index].title = countryName
. также вам необходимо перезагрузить эту строку/заполнить данные табличного представления.4. Исправил это. Спасибо @GhulamMustafa. Я приношу извинения за поздний ответ.
Ответ №2:
- Первый Контроллер:
- «Выбор страны» подтвердите этот делегат в своем первом контроллере
- Затем передайте/Сохраните свой индекс выбора ячейки FirstViewController.
- Перейдите к контроллеру вашей страны, выберите страну, передайте ее через «функция Выбранная страна(страна: Строка,индекс: Int) {}» , Обновите пользовательские данные/массив.
- Наконец, обновите представление таблицы с помощью обновленных пользовательских данных.
класс FirstViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,CountrySelectionDelegate {
@IBOutlet weak var yourFirstTable: UITableView! var customData = [Details(title: "Title-1", country: ""),Details(title: "Title - 2", country: ""),] override func viewDidLoad() { super.viewDidLoad() } func selectedCountry(country: String,index: Int) { self.customData[index].country = country yourFirstTable.reloadData() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return customData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DetailTableCell let custInfo = customData[indexPath.row] cell.yourTitleLabel.text = "Title: " custInfo.title cell.yourCountryLabel.text = (custInfo.country.count > 0 ? "Country: (custInfo.country)" : "Country: ---") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryViewController") as? CountryViewController nextVC?.selectedIndex = indexPath.row nextVC?.delegate = self self.navigationController?.pushViewController(nextVC!, animated: true) } }
- CountryViewController:
импорт UIKit
protocol CountrySelectionDelegate { func selectedCountry(country: String, index:Int) } class CountryViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var countryTable: UITableView! var selectedIndex: Int = 0 let countryList = ["India","USA","UK","Nepal","Bangladesh","Pakistan","Bhutan"] weak var delegate: CountrySelectionDelegate? override func viewDidLoad() { super.viewDidLoad() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return countryList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CountryTableViewCell cell.countryLabel.text = countryList[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.selectedCountry(country: countryList[indexPath.row], index: selectedIndex) self.navigationController?.popViewController(animated: true) } }