Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Add sub view in from a class

dickthedevdickthedev Posts: 214Registered Users @ @
edited April 29 in iOS SDK Development
Hello, I am new to Swift. I copied a snippet of code to add a UIView programmatically to a
ViewController. The code below works perfectly.
import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let myView=UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 200))
        
        // Change UIView background colour
        myView.backgroundColor=UIColor.lightGray
        
        // Add rounded corners to UIView
        myView.layer.cornerRadius=25
        
        // Add border to UIView
        myView.layer.borderWidth=2
        
        // Change UIView Border Color to Red
        myView.layer.borderColor = UIColor.red.cgColor
        
        // Add UIView as a Subview
        self.view.addSubview(myView)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

For exercise purpose, I want to move the new view into a class
import UIKit

class MyView: UIView {

    let myView=UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 200))
    // Change UIView background colour
    //myView.backgroundColor=UIColor.lightGray.backgroundColor=UIColor.lightGray
  

}
This work fine BUT as soon as I commented out the line //myView.backgroundColor=UIColor.lightGray.backgroundColor=UIColor.lightGray
Xcode gives me an error "Expected declaration" just what declaration is it expecting? I thought I already declared it in let myView=UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 200))

What am I missing?

I have Xcode 8.3.2

Thanks.
Sign In or Register to comment.