![](/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.