create a view in swift

Here's an example of creating a basic UIView in Swift:

  1. First, create a subclass of UIView:
main.swift
class MyView: UIView {
    
}
30 chars
4 lines
  1. Override the init(frame:) initializer to customize your view:
main.swift
class MyView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // Customization code goes here
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
266 chars
13 lines
  1. Add your custom subviews and layout constraints in the init(frame:) method:
main.swift
class MyView: UIView {
    
    let myLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        myLabel.text = "Hello, world!"
        myLabel.textAlignment = .center
        addSubview(myLabel)
        
        myLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            myLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            myLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
638 chars
24 lines
  1. You can then use your custom view in a view controller:
main.swift
class MyViewController: UIViewController {
    
    let myView = MyView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(myView)
        
        myView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            myView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            myView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            myView.topAnchor.constraint(equalTo: view.topAnchor),
            myView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
    
}
605 chars
20 lines

Note that this is just a basic example, and you can add as much customization and complexity as you need for your specific use case.

gistlibby LogSnag