【发布时间】:2019-03-27 06:41:32
【问题描述】:
我正在创建一个应用程序,其中的菜单在TableViewCell 中列出。菜单已经在单元格内,但不幸的是,当我单击其中一个菜单时,它没有执行菜单应该执行的操作。例如,我点击了logout label,它没有执行showlogoutDialog。我已经使用了断点,但表中的数据似乎只是纯文本。下图是表格的示例输出。希望你能就这个问题给出一些解决方案。谢谢。
DoctorMenuTableCell.swift
class DoctorMenuTableCellTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
MoreOptionViewController.swift
private let menuIdentifier = "MenuCell"
class MoreOptionViewController: UIViewController {
@IBOutlet weak var doctorMenuTableView: UITableView!
}
override func viewDidLoad() {
super.viewDidLoad()
self.doctorMenuTableView.dataSource = self
self.doctorMenuTableView.delegate = self
}
//MARK: Function
func showLogoutDialog() {
//create alert
let alert = UIAlertController(title: "Confirmation", message: "Are you sure you want to logout?", preferredStyle: .alert)
//add the actions (button)
alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert) in
self.logout()
}))
self.present(alert, animated: true, completion: nil)
}
func logout() {
NotificationCenter.default.post(name: Notification.Name(deleteUserDataNotificationName), object: nil)
}
}
extension MoreOptionViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return Menu.More.items.count
default: return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: menuIdentifier, for: indexPath) as! DoctorMenuTableCell
cell.titleLabel.text = Menu.More.items[row].value
if row == 1{
cell.titleLabel.textColor = UIColor.red
cell.accessoryType = .none
}
return cell
default:
return UITableViewCell()
}
}
func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0: break
case 1:
switch indexPath.row {
case 0:
let alertController = UIAlertController(title: "Info", message: "No available data", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
case 1: showLogoutDialog()
default: break
}
default: break
}
}
【问题讨论】:
-
你差不多完成了,你只是搞砸了
Switch案例。在下面查看我的答案以了解您做错了什么。 -
有时,尤其是当您在 ViewController 中使用 tableView 而不是 TableViewController 时,您需要添加 numberOfSection = 1 或(您需要多少)。之后它开始按预期工作
标签: ios swift xcode uitableview