gpt4 book ai didi

ios - 如何在 TableView 单元格和.xib 中添加警报操作(swift 3)

转载 作者:行者123 更新时间:2023-11-30 12:22:51 25 4
gpt4 key购买 nike

我是 Swift 世界的 super 初学者。

我在 Main.Storyboard 中使用 UITableView,在 .xib 文件中,我使用 UITableViewCell

这是 ViewController.swift 中与 UITableView 相关的一些代码:

@IBOutlet weak var friendsTableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

friendsTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
let entry = contacts[(indexPath as NSIndexPath).row]

cell.configureWithContactEntry(entry)
cell.layoutIfNeeded()

return cell
}

这是TableViewCell.swift中的代码,与TableViewCell.xib相关。

@IBOutlet weak var contactNameLabel: UILabel!
@IBOutlet weak var contactPhoneLabel: UILabel!

override func layoutIfNeeded() {
super.layoutIfNeeded()
}

func configureWithContactEntry(_ contact: ContactEntry) {
contactNameLabel.text = contact.name
contactPhoneLabel.text = contact.phone ?? ""

}

并且,在 TableViewCell.xib 中,我使用 UITableViewCell,2 个标签。

在这种情况下,当我按下表格单元格之一时,如何添加 AlertAction?

最佳答案

您必须将alertViewController 添加到TableViewController 而不是单元格本身。但是,正如您希望在用户触摸单元格后显示警报 View 一样,只需实现 tableViewDidselectRow 并从那里显示您的警报 View

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let alert = UIAlertController(title: "Alert", message: "This is an Alert", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}

现在,通过触摸单元格,它将显示警报

关于ios - 如何在 TableView 单元格和.xib 中添加警报操作(swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44583859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com