user1837779
user1837779

Reputation: 295

How to change background view color partialy in ios swift

New to swift i want my background view 80% height to be red and rest in blue. Currently i'm doing that adding two views. I think there is a direct way to do that. Any guidance or help will be appreciated.

Upvotes: 2

Views: 1030

Answers (2)

user1837779
user1837779

Reputation: 295

Thanks for help. I think i found a solution.Adding a sublayer does the trick.

self.view.backgroundColor = UIColor.red
let bottomBorder = CALayer()
let t = CGRect(x: 0.0, y: (self.view.frame.size.height/100.0)*80, width: self.view.frame.size.width, height: (self.view.frame.size.height/100.0)*20)
bottomBorder.frame = t
bottomBorder.backgroundColor = UIColor.blue.cgColor
self.view.layer.addSublayer(bottomBorder)

Upvotes: 1

Francois Nadeau
Francois Nadeau

Reputation: 7463

Adding two views is a good way of getting what you want (and the best since you can set the % via constraints.)

An other way would be by adding sublayers to your view via the code:

let gradient: CAGradientLayer = CAGradientLayer()
let topColor = UIColor(red:223.0/255.0, green:142.0/255.0, blue:219.0/255.0, alpha:255.0/255.0).cgColor
let bottomColor = UIColor(red:0, green:201.0/255.0, blue:243.0/255.0, alpha:255.0*0.34).cgColor
gradient.colors = [topColor, UIColor.clear, bottomColor]
gradient.locations = [0.0 , 0.5, 1.0]
gradient.frame = self.view.bounds
self.view.layer.insertSublayer(gradient, at: 1)

I would only use the layer method if you want to do something funky like a gradient.

Upvotes: 6

Related Questions