无法使用UI按钮呈现第二个UIviewcontroller

时间:2018-04-10 17:00:58

标签: ios swift uiviewcontroller

我正在创建一个简单的应用程序,它有两个按钮,可以转到两个不同的viewcontroller。监视列表按钮不起作用时,警报按钮正在工作。这是我的代码。

import UIKit

class ViewController: UIViewController {

let alertButton = UIButton(type: .system)
let watchListButton = UIButton(type: .system)

override func viewDidLoad() {
    super.viewDidLoad()

    //alert button
    self.view.addSubview(alertButton)
    alertButton.setTitle("  Alert  ", for: UIControlState.normal) // what is UIControleState.normal?
    alertButton.translatesAutoresizingMaskIntoConstraints = false
    alertButton.backgroundColor = .green
    alertButton.frame.size = CGSize(width: 250, height: 500)
    alertButton.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 60).isActive = true
    alertButton.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 220).isActive = true

    alertButton.addTarget(self, action: #selector(nextPg), for: UIControlEvents.touchUpInside)


    //watch list button
    self.view.addSubview(watchListButton)
    watchListButton.setTitle("  Watchlist  ", for: UIControlState.normal) // what is UIControleState.normal?
    watchListButton.translatesAutoresizingMaskIntoConstraints = false
    watchListButton.backgroundColor = .green
    watchListButton.frame.size = CGSize(width: 150, height: 200)

    watchListButton.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 60).isActive = true
    watchListButton.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 30).isActive = true

    alertButton.addTarget(self, action: #selector(wlPage), for: UIControlEvents.touchUpInside)

}
@objc func wlPage() {

    let wlp = watchListController()
    present(wlp, animated: true, completion: nil)

}

@objc func nextPg() {

    let wllc = AlertListController()
    present(wllc, animated: true, completion: nil)

}

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


}

运行时,这是我在xcode中得到的错误

Simulator user has requested new graphics quality: 100
Warning: Attempt to present <newApp.watchListController: 0x7f887851f600> on <newApp.ViewController: 0x7f887850a0d0> whose view is not in the window hierarchy!

我可以知道发生了什么,我该如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:0)

对于第二个按钮,您再次在第一个按钮上调用addTarget。因此,当您按下警报按钮时,它会尝试同时显示两个viewControllers,而第二个present会失败。 watchList按钮实际上什么也没做。

改变这个:

alertButton.addTarget(self, action: #selector(wlPage), for: UIControlEvents.touchUpInside)

为:

watchListButton.addTarget(self, action: #selector(wlPage), for: UIControlEvents.touchUpInside)

此外,在按钮上设置translatesAutoresizingMaskIntoConstraints = false表示不会使用其frame。您应该为按钮的宽度和高度设置约束,而不是设置.frame.size