从故事板外的视图访问UIControl

时间:2018-03-10 19:09:55

标签: ios swift xcode

我的视图(在Main.storyboard中)包含另一个UIView,它只占屏幕高度的80%左右(使用约束设置)。

在第二个视图中(我称之为viewContainer)我希望显示不同的视图,这些视图可以使用 viewContainer.bringSubview(toFront: someView)

我在项目中创建了一个新组,其中包含3个UIViewController类和3个xib文件,我希望在viewContainer中显示这些文件。

对于每个xib文件,我将背景颜色更改为独特的颜色,以便我可以判断它是否正常工作。它到目前为止。

现在我尝试将UIButton添加到第一个UIViewController类,并为其添加了@IBAction。这只是将文本打印到控制台。

当我运行应用程序时,我可以在我的3个类(3种不同的背景颜色)之间切换,当我选择它时,我也可以看到并单击我添加到第一个类的按钮。

但是代码永远不会被执行而我的控制台是空的。这是因为我的其他3个观点未显示在我的Main.storyboard

Project Structure Screenshot

SimpleVC1.swift

import UIKit

class SimpleVC1: UIViewController {    
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func onButtonPressed(_ sender: Any) {
        print("test")
    }

}

1 个答案:

答案 0 :(得分:0)

尝试使用目标(并以编程方式创建按钮),它可能更容易:

import UIKit

class SimpleVC1: UIViewController {

    var button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(button)
        button.frame.size = CGSize(width: 100, height: 100)
        button.center = CGPoint(x: 100, y: 100)
        button.setTitle("Control 1", for: .normal)
        button.addTarget(self, action: #selector(control1), for: .touchUpInside)
        button.backgroundColor = UIColor.blue
        button.setTitleColor(UIColor.white, for: .normal)
    }

    @objc func control1() {
        //Add your code for when the button is pressed here
        button.backgroundColor = UIColor.red
    }
}