【问题标题】:Alert and tableViewCell [duplicate]警报和 tableViewCell [重复]
【发布时间】:2016-08-11 23:09:06
【问题描述】:

如何点击 UITableView 的单元格,然后它会出现一个警报,我可以在“确定”或“取消”之间进行选择。

如果点击“确定”,应用会显示一个设置控制器(我已经拥有)。

如果点击“取消”,警报就会消失并且什么也不会发生。

【问题讨论】:

标签: ios swift uitableview alert


【解决方案1】:

概述:

1.设置表格视图委托

如果您使用UITableViewControllerUITableViewDelegate 已经设置为表视图控制器类,否则请自行设置 (tableView.delegate = self)。

2。点击单元格时调用的函数

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

3.使用演示控制器显示警报视图

代码:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            
    let alertController = UIAlertController(title: "Something", message: "bla bla", preferredStyle: .Alert)
    
    let okAction = UIAlertAction(title: "Ok", style: .Default) { action in

        //Do something when cancel is tapped
        
        let setupController = UIViewController() //Replace with your own set up view controller
        
        self.presentViewController(setupController, animated: true) {
            //Do something when alert view is presented
        }
    }
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in
        
        //Do something when cancel is tapped
    }
    
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)
    
    //Show alert view
    presentViewController(alertController, animated: true) {
        //Do something when alert view is presented
    }
}

【讨论】:

  • self.presentViewController(setupController, animated: true) { 行我收到错误“无法将'nameOfMySetupController'.type 类型的值转换为预期的参数类型UIViewController
  • 您首先需要创建一个设置控制器的实例。假设您的视图控制器的名称是 nameOfMySetupController,请执行以下操作:let setupController = nameOfMySetupController()。以我的拙见,如果您在开始编码之前学习一些 Swift / iOS 编程的基础知识会有所帮助。
  • 现在它没有给我任何错误。但是警报没有出现。如何选择我必须点按才能显示警报的行?
【解决方案2】:

您需要重写方法tableView:didSelectRowAtIndexPath:,如下所示

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let ac = UIAlertController(title: "Title", message: "Your message here", preferredStyle: .Alert)
        let okAction = UIAlertAction(title: "Ok", style: .Default) { (_) in
            presentViewController(yourSetupController, animated: true, completion: nil)

        }
        ac.addAction(okAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
        ac.addAction(cancelAction)
        presentViewController(ac, animated: true, completion: nil)
    }

【讨论】:

  • 还有你的代码在presentViewController(yourSetupController, animated: true, completion: nil) 行,我得到错误“无法将'nameOfMySetupController'.type 类型的值转换为预期的参数类型UIViewController –
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
相关资源
最近更新 更多