baileymiller2017
baileymiller2017

Reputation: 175

swift playgrounds display uiview with nonstop looping

I create and display uiview in live view windows, when i create the button and add to the uiview , the program fail with nonstop looping which continuously load addbutton . Did somebody meet this problem and please tell me why :-)

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()

enter image description here

Upvotes: 0

Views: 200

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You add the button here

view.addSubview(btn)

inside addnewbutton

which recursively searches for the parent view of the VC and it's not yet setted inside loadView so control calls it again and the problem happens to infinite loop , so comment that line and uncomment this

view.addSubview(k1) // which is inside loadView

BTW make the return of addnewbutton to UIButton directly instead of a cast

Upvotes: 1

Related Questions