ios - 点击表格单元格时如何推送新的 View Controller ?

标签 ios swift uitableview navigationcontroller

我创建了这个包含 3 个部分和 7 行的表。代码如下所示

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var subjectTabelView: UITableView!

var slSubject = ["English Lang&Lit", "Chinese Lang&Lit", "Economics"]
var hlSubject = ["Mathematics", "Chemistry", "Biology"]
var tokSubject = ["Theory of Knowledge"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    subjectTabelView.dataSource = self
    subjectTabelView.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 3
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0{
        return hlSubject.count
    }else if section == 1{
        return slSubject.count
    }else {
        return tokSubject.count
    }

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let subjectCell = tableView.dequeueReusableCellWithIdentifier("idSubjectCell", forIndexPath: indexPath) as! UITableViewCell

    if indexPath.section == 0 {
        subjectCell.textLabel?.text = hlSubject[indexPath.row]
    } else if indexPath.section == 1{
        subjectCell.textLabel?.text = slSubject[indexPath.row]
    } else {
        subjectCell.textLabel?.text = tokSubject[indexPath.row]
    }

    return subjectCell
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "HL"
    } else if section == 1{
        return "SL"
    } else {
        return "ToK"
    }
}



}

我需要做什么才能使该表中的每个单元格在点击时推送一个新的 View Controller ?我的 Storyboard的图片如下所示。在我的 Storyboard,我的 View Controller 中,我已经创建了一个导航 Controller ,并将具有该表的 View Controller 设置为 rootViewController。目前,我的 tableView 只有一个原型(prototype)单元格和一个单元格标识符。

谢谢!

最佳答案

假设您的“locationVC”是:

class LocationVC: UIViewController {

    @IBOutlet weak var fromWhereLabel: UILabel!
    //This can be changed when creating this UIViewController
    var textToShow : String?

    override func viewWillAppear(animated: Bool) {
        if let textToShow = textToShow {
            fromWhereLabel.text = textToShow
        }
    }
}

然后,只需将下面的函数添加到 ViewController 中名为 UIViewController 的代码中(应该有一个更好的名称;-) )你可以实现你的目标。

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
      //if such cell exists and destination controller (the one to show) exists too..
        if let subjectCell = tableView.cellForRowAtIndexPath(indexPath), let destinationViewController = navigationController?.storyboard?.instantiateViewControllerWithIdentifier("locationVC") as? LocationVC{
            //This is a bonus, I will be showing at destionation controller the same text of the cell from where it comes...
            if let text = subjectCell.textLabel?.text {
                destinationViewController.textToShow = text
            } else {
                destinationViewController.textToShow = "Tapped Cell's textLabel is empty"
            }
          //Then just push the controller into the view hierarchy
          navigationController?.pushViewController(destinationViewController, animated: true)
        }
     }

每次点击单元格时,您都可以启动 LocationVC UIViewController,并且它将具有一定的值(value)来证明它的正确性。 :)

希望有帮助!

UPDATE: Code and Instructions below are for allowing to launch different UIViewControllers after tap on cells

1.- 让我们创建一个类,它将成为每个新 UIViewController 的父类(我们愿意从表格 View 单元格的点击中进入的类):

public class CommonDataViewController: UIViewController {
//Here we are going to be putting any data we want to share with this view
  var data: AnyObject?
}

2.- 让我们创建某种导航规则,以便进行组织;-)

enum Navigation: Int {
    case vc1 = 0, vc2 = 1, vc3 = 2, vc4 = 3
    //How many rules we have (for not to exceed this number)
    static let definedNavigations = 4
    //This must return the identifier for this view on the Storyboard
    func storyboardIdentifier() -> String {
        //for this example's sake, we have a common prefix for every new view controller, if it's not the case, you can use a switch(self) here
        return "locationVC_\(self.rawValue + 1)"
    }
}

现在,让我们以之前的代码为基础:

3.- 为了清楚起见,让我们稍微更改一下之前的 LocationVC(在本例中,将有一个带有文本 “locationVC_1”的 Storyboard Identifier )

class LocationVC: CommonDataViewController {

    @IBOutlet weak var fromWhereLabel: UILabel!

    //This is optional, but improves clarity..here we take our AnyObject? variable data and transforms it into the type of data this view is excepting 
    var thisVCReceivedData: String? {
        return data as? String
    }

    override func viewWillAppear(animated: Bool) {
        if let textToShow = thisVCReceivedData {
            fromWhereLabel.text = textToShow
        }
    }
}

4.- 现在,我们在 didSelectRowAtIndexPath 函数中触发所有这些。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //Just to avoid tapping on a cell that doesn't have an UIViewController asociated
    if Navigation.definedNavigations > indexPath.row {
        //The view's instance on our Navigation enum to which we most go after tapping this cell
        let nextView = Navigation(rawValue: indexPath.row)!
        //The identifier of the destination CommonDataViewController's son in our Storyboard
        let identifier = nextView.storyboardIdentifier()
        //If everything exists...
        if let subjectCell = tableView.cellForRowAtIndexPath(indexPath), let destinationViewController = navigationController?.storyboard?.instantiateViewControllerWithIdentifier(identifier) as? CommonDataViewController {

            //here you can use a switch around "nextView" for passing different data to every View Controller..for this example, we just pass same String to everyone
            if let text = subjectCell.textLabel?.text {
                destinationViewController.data = text
            } else {
                destinationViewController.data = "Tapped Cell's textLabel is empty"
            }
            navigationController?.pushViewController(destinationViewController, animated: true)
        }
    }
}

Notice that you can achieve same results using protocols and delegate approach, this is just simpler to explain

关于ios - 点击表格单元格时如何推送新的 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32014001/

相关文章:

iphone - 获取 UITableView 周围的边框,如 UIActionSheet

iphone - 在 iOS Safari 上更改方向时出现白色闪烁

html - 使用 Swift 在 iOS 上将带有 HTML 标记的描述转换为 NSAttributedString 时如何使用旧金山字体

iphone - 为什么我的 UITableViewCell 没有 textLabel 属性?

ios - recordID 的值类型为引用,无法查询

ios - 在 UITableViewController 中重新排序行后 UI 更新不正确

iphone - 提醒应用程序 UI 是如何创建的?

android - Flutter AppBar 上方有多余空间

ios - Cocos2D + 仅禁用 Retina iPad 图形

iphone - 24小时模拟时钟