我在实时视图窗口中创建并显示uiview,当我创建按钮并将其添加到uiview时,程序会因不间断循环而失败,并不断加载addbutton。有人遇到这个问题了吗,请告诉我原因:-)
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var label1 : UILabel?
override func loadView() {
let view = UIView()
view.backgroundColor = .white
print("code run here ")
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
label1 = label
view.addSubview(label)
let k1:UIButton = addnewbutton() as! UIButton
//view.addSubview(k1)
self.view = view
}
@objc func buttonPressed(sender: UIButton!) {
var alertController = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
self.present(alertController, animated: true, completion: nil)
}
func addnewbutton() -> UIView{
var btn : UIButton
btn = UIButton()
btn.frame = CGRect(x:200,y:300,width:100,height:25)
btn.setTitle("clickme",for: UIControlState.normal)
//btn.titleLabel?.text = "clickme"
btn.backgroundColor = UIColor.black
btn.titleLabel?.textColor = UIColor.white
btn.titleColor(for: UIControlState.normal)
btn.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.touchUpInside)
view.addSubview(btn)
return btn
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
答案 0 :(得分:1)
您在此处添加按钮
fetch
在view.addSubview(btn)
内
它以递归方式搜索VC的父视图,并且尚未在addnewbutton
中设置它,因此控件再次调用它,问题就发生了无限循环,因此请注释该行并取消注释
loadView
顺便说一句,view.addSubview(k1) // which is inside loadView
直接返回addnewbutton
,而不是强制转换