我正在尝试从我的UiView初始化视图控制器。但是我在self.presentViewController(vc,动画:true,completion:nil)这行上出错了。我正试图在单击表行后显示另一个视图控制器。我已经初始化了故事板。

import UIKit

class CustomSwipeOut: UIView , UITableViewDataSource , UITableViewDelegate {

    var label: UILabel = UILabel()
     var myNames = ["item1","item2","item3"]

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addCustomView()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func addCustomView()
    {
       //add blank subview to the view
        var blankView : UIView = UIView(frame: CGRectMake(0, 0, 300, 100))
        blankView.backgroundColor = UIColor.greenColor()
        self.addSubview(blankView)

        //creating a tableview programmatically
        var tblView : UITableView = UITableView()
        tblView.frame = CGRectMake(0, 100, 300, 200)
        self.addSubview(tblView)
        tblView.delegate = self
        tblView.dataSource = self
        tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")

    }

    //pragma mark- table view data source methods
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as UITableViewCell
        cell.textLabel?.text = self.myNames[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.myNames.count
    }

    //pragma mark - table view delegate methods

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

        switch indexPath.row {
        case 0:
            println("index o clicked")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("MoneySum") as UIViewController
            self.presentViewController(vc, animated: true, completion: nil)
        case 1:
            println("index 1 clicked")
        case 2:
            println("index 2 clicked")
        default:
            println("no index")
        }
    }
}

最佳答案

presentViewController:animated:completion:是仅为UIViewController定义的方法,而不是为UIViewsee Apple doc here)。
您的UIView可能位于由UIViewController管理的视图层次结构中。
解决方案是使用对父UIViewController的引用并对其调用presentViewController:animated:completion:

关于ios - 如何从SWIFT中的UIView实例化ViewController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29094106/

10-11 04:25