How to create custom view programmatically in swift having controls text field, button etc

前端 未结 5 1856
星月不相逢
星月不相逢 2020-12-08 12:51

I am trying to access the MyCustomView from another class using the following code in ViewController.swift ..

var view = MyCustomView(frame: CGR         


        
相关标签:
5条回答
  • 2020-12-08 13:30
    let viewDemo = UIView()
    viewDemo.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
    self.view.addSubview(viewDemo)
    
    0 讨论(0)
  • 2020-12-08 13:34

    Swift 3 / Swift 4 Update:

    let screenSize: CGRect = UIScreen.main.bounds
    let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
    self.view.addSubview(myView)
    
    0 讨论(0)
  • 2020-12-08 13:36
    view = MyCustomView(frame: CGRectZero)
    

    In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.

    0 讨论(0)
  • 2020-12-08 13:38
    var customView = UIView()
    
    
    @IBAction func drawView(_ sender: AnyObject) {
    
        customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
        customView.backgroundColor = UIColor.black     //give color to the view 
        customView.center = self.view.center  
        self.view.addSubview(customView)
           }
    
    0 讨论(0)
  • 2020-12-08 13:43

    The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

    But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

    customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
    self.view.addSubview(customView)
    

    Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

    0 讨论(0)
提交回复
热议问题