![](/img/trans.png)
[英]Difference between self.view.addSubview and view.addSubview
[英]view.addSubview(: ) Not working in swift playgrounds
我有一个快速的游乐场,并创建了一个名为“ startButton”的UIButton。
我有一个函数可以设置UIButton的参数。
func setupStartButton() {
startButton.frame = CGRect(x: 15, y: 550, width: 125, height: 50)
startButton.backgroundColor = UIColor(ciColor: CIColor(red: 255/255, green: 0/255, blue: 77/255, alpha: 1.0))
startButton.layer.cornerRadius = 20
startButton.setTitle("Start", for: .normal)
startButton.setTitleColor(.white, for: .normal)
startButton.addTarget(self, action: #selector(startButtonPressed), for: .touchUpInside)
view.addSubview(startButton)
}
我在viewDidLoad中称它为
override func viewDidLoad() {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 524, height: 766))
view.backgroundColor = .white
setupStartButton()
PlaygroundPage.current.liveView = view
PlaygroundPage.current.needsIndefiniteExecution = true
}
当我运行游乐场时,它不显示按钮。
如何显示按钮。
谢谢
您正在将PlaygroundPage.current.liveView
设置为在viewDidLoad
创建的本地view
。 这与视图控制器的视图不同,这是您要在setupStartButton
中添加按钮的setupStartButton
。
我将删除以下行: let view = UIView(frame: CGRect(x: 0, y: 0, width: 524, height: 766))
然后每个对view
引用将成为视图控制器的视图。
您应该从viewDidLoad
方法中删除游乐场代码。 在视图控制器类之后,您可以创建视图控制器的实例并设置游乐场:
就像是:
class MyViewController: UIViewController {
// your code
}
PlaygroundPage.current.liveView = MyViewController()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.