Search code examples
swiftxcodeuibackgroundcolor

How to split the background color of UIView in Swift?


I want to differentiate the background color in my app screen horizontally.

I have tried this, it's going nowhere.

var halfView1 = backgroundView.frame.width/2
backgroundView.backgroundColor.halfView1 = UIColor.black

backgroundView is an outlet from View object on storyboard

For example, half of the screen is blue and another half of the screen is red.


Solution

  • You should create a custom UIView class and override draw rect method

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            self.view.addSubview(HorizontalView(frame: self.view.bounds))
        }
    }
    class HorizontalView: UIView {
        override func draw(_ rect: CGRect) {
            super.draw(rect)
    
            let topRect = CGRect(x: 0, y: 0, width: rect.size.width/2, height: rect.size.height)
            UIColor.red.set()
            guard let topContext = UIGraphicsGetCurrentContext() else { return }
            topContext.fill(topRect)
    
            let bottomRect = CGRect(x: rect.size.width/2, y: 0, width: rect.size.width/2, height: rect.size.height)
            UIColor.green.set()
            guard let bottomContext = UIGraphicsGetCurrentContext() else { return }
            bottomContext.fill(bottomRect)
        }
    }
    

    enter image description here