【问题标题】:Directing to a different ViewController depending on tableView cell clicked根据单击的 tableView 单元格定向到不同的 ViewController
【发布时间】:2016-01-16 20:10:29
【问题描述】:

我正在尝试根据单击的 tableView 单元格呈现 viewController。

目前,如果他们都被点击,他们会重定向到同一个 viewController,我将如何改变这个?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
    cell.cellLabel.text = self.objects.objectAtIndex(indexPath.row) as! String

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("other", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "other"){

        var upcoming: otherViewController = segue.destinationViewController as! otherViewController

        let indexPath = self.tableView.indexPathForSelectedRow!

        let titleString = self.objects.objectAtIndex(indexPath.row) as! String

        upcoming.titleString = titleString

        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)


    }
}

我可以在 cellLabel.text 上做一个 if else 吗?如 if (cellLabel.text == "option8"){ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("option8", sender: self) }

}

我正在使用 Swift 和 xcode7。

【问题讨论】:

    标签: ios swift uitableview xcode7


    【解决方案1】:

    不要也永远不要与cellLabel.text 进行比较,请考虑使用indexPath.row。然后在情节提要中为您需要的每个视图控制器添加不同的转场。代码将是这样的:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row == 0 || indexPath.row == 2{
       self.performSegueWithIdentifier("other", sender: self)
    }
    else{
      self.performSegueWithIdentifier("other", sender: self)
    }
    
    }
    

    【讨论】:

    • 是不是因为indexPath比较准确?或者这只是适当的做法?也谢谢你
    • 比较整数而不是字符串时它更准确。以及它的最佳实践,假设您随时更改显示的文本,如果是字符串,则必须更改比较代码,但如果使用 indexPath,则不需要
    • 其他是什么意思。其他名称或其他想法?
    【解决方案2】:

    是的,你可以。

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        if cell.cellLabel.text == "option8" {
            self.performSegueWithIdentifier("other8", sender: self)
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以根据可以重定向到特定控制器的行号检查 didSelectrow 中的 indexpath.row。

      【讨论】:

        猜你喜欢
        • 2021-11-28
        • 2013-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        相关资源
        最近更新 更多