以编程方式关闭弹出视图

时间:2016-04-02 23:13:14

标签: ios swift uiviewcontroller uibutton

我试图以编程方式弹出一个视图,但遇到了麻烦。

import UIKit

class CreatePostViewController: UIViewController {

    var isAnimating: Bool = false
    var dropDownViewIsDisplayed: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        createDescriptionField()
        createLabels()
        createInputFields()
        createBackButton()

    }
    //More code omitted 

    func createBackButton(){
        let button = UIButton()
        button.setTitle("back", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button.frame = CGRectMake(200,200,100,50)
        button.backgroundColor = UIColor.redColor()
        button.addTarget(self, action: "goBack:", forControlEvents: .TouchUpInside)
        self.view.addSubview(button)

    }

    func goBack(sender: UIButton){
        navigationController?.popToRootViewControllerAnimated(true)

    }

}

我从另一个类添加这个类:

import UIKit

class HomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        needCashButton()
    }

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

    func needCashButton(){

        let image = UIImage(named: "GlossyRoundedButton.png") as UIImage?
        let button = UIButton()
        button.setTitle("Do Job", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button.setBackgroundImage(image, forState: .Normal)
        button.frame = CGRectMake(225,200,100,50)

        button.addTarget(self, action: "cashButtonPressed:", forControlEvents: .TouchUpInside)
        self.view.addSubview(button)

    }


    func cashButtonPressed(sender: UIButton){
        let findJob = CreatePostViewController()
        self.presentViewController(findJob, animated: false, completion: nil)
    }

}

我阅读了很多其他帖子,建议我只使用行navigationController?.popToRootViewControllerAnimated(true)弹出CreatePostViewController,但是当我点击按钮时,它没有做任何事情。有什么我在这里俯瞰的吗?

2 个答案:

答案 0 :(得分:1)

如果你的UIViewController在UINavigationViewController中是 NOT (或者它是以模态方式呈现的),请使用它来解除它:

self.dismissViewControllerAnimated(true, completion: nil)

如果你在UINavigationViewController中有它,请使用它来解除它:

self.navigationController.popViewControllerAnimated(true)

答案 1 :(得分:0)

navigationController仅在您实际使用导航控制器:)时才有效。所以我建议使用类似的东西

let vc = UINavigationController(rootViewController: CreatePostViewController())
self.presentViewController(vc, animated: false, completion: nil)
相关问题