【问题标题】:How to change view when tapping button in a custom UITableViewCell在自定义 UITableViewCell 中点击按钮时如何更改视图
【发布时间】:2015-02-16 12:39:48
【问题描述】:

通常,我会这样改变视图:

var goBackToMainView:MainViewController = self.storyboard?.instantiateViewControllerWithIdentifier("navigation2") as MainViewController

self.presentViewController(goBackToMainView, animated: true, completion: nil)

但是,如果我在用户点击按钮时尝试在自定义 UITableViewCell 中执行此操作,则会出现 customTableViewCell does not have a member named 'storyboard' and 'presentViewController' 之类的错误

如何更改 TableViewCell 中的视图?

【问题讨论】:

    标签: uitableview button swift uiviewcontroller


    【解决方案1】:

    为什么要在 UITableViewCell 子类中做呢?您应该在 ViewController 中进行视图管理。

    在您的视图控制器中:

    import UIKit
    
    // Take note of UITableViewDelegate, you'll need it to be able to use
    // tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    class MyTableViewController: UITableViewController, UITableViewDelegate {
    
        // Assuming that you have a storyboard variable in AppDelegate
        let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    
        // .. more code here like viewDidLoad, etc.
    
        override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
            var viewController = appDelegate.storyboard.instantiateViewControllerWithIdentifier("MainViewController") as MainViewController
    
            // This will probably appear as a modal
            self.presentViewController(viewController, animated: true, completion: nil)
        }
    
    }
    

    注意:我刚刚为上面的代码做了一个快速的操场,所以你可能需要解开可选项。

    如果您将视图控制器嵌入到导航控制器中,您可能需要使用 Unwind Segues。更多信息请点击此处:What are Unwind segues for and how do you use them?

    干杯!

    【讨论】:

    • 因为我不想改变视图用户点击按钮而不是单元格
    【解决方案2】:

    您是否尝试过添加为子视图?

    例子:

    var tableViewCell = UITableViewCell(frame: aFrame)
    
    tableViewCell.addSubview(aView)
    

    【讨论】:

    • 如果我不能使用self.storyboard,我如何获得aView?
    • 所以你的 tableViewCell 来自故事板?您在哪里创建要添加/更改到/在 UITableViewCell 中的“子”视图?
    • 我在情节提要中创建了另一个视图
    • 您是否在 UITableViewCell 中创建了 StoryBoard 的链接?喜欢...var storyboard = UIStoryBoard(storyboardWithName: "something", bundle: nil)
    • 谢谢,现在我的故事板变量正在工作,我需要做什么才能获得 presentViewController 功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    相关资源
    最近更新 更多