How to change background color of UITextField to custom gradient color in iOS using Swift - ios

I have done gradient coloring before for changing color of my parent view now I am using same method to change the background color of UITextField but its not working.
This is the method I used for my view:
func setGradientBackgroundOfView()
{
// assigning gradient color to background View
let endingColorOFGradient = UIColor(colorLiteralRed: 133/255, green: 210/255, blue: 230/255, alpha: 1.0).CGColor
let startingColorOfGradient = UIColor(colorLiteralRed: 50/255, green: 189/255, blue: 170/255, alpha: 1.0).CGColor
gradient.startPoint = CGPoint(x: 0.5, y: 0.0)
gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
gradient.colors = [startingColorOfGradient , endingColorOFGradient]
self.view.layer.insertSublayer(gradient, atIndex: 0)
}
And this method for setting layer:
override func viewWillLayoutSubviews() {
gradient.frame = self.view.bounds
}
I am calling my setGradientBackgroundOfView() in viewDidLoad() and it's working perfect but if I change
self.view.layer.insertSublayer(gradient, atIndex: 0)
with
self.textFieldUserName.layer.insertSublayer(gradient, atIndex: 0)
it does not work. What am I missing here?

Related

incorrect Navigation bar background image coloring for iphone 12 mini

I'm setting the image of the navigation bar to a gradient. This works perfectly on all models except for iPhone 12 mini.
I've tried calling this on my main view controller in ViewWillAppear, viewDidAppear, and ViewDidLoad
Here's what it looks like on all other models
func setNavGradiant(){
guard let navigationController = self.navigationController else {print("❇️♊️>>>\(#file) \(#line): guard let failed<<<"); return}
let gradientLayer = CAGradientLayer()
var updatedFrame = navigationController.navigationBar.bounds
updatedFrame.size.height += UIApplication.shared.windows[0].windowScene?.statusBarManager?.statusBarFrame.height ?? 0
gradientLayer.frame = updatedFrame
gradientLayer.colors = [ #colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1).cgColor, #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1).cgColor] // start color and end color
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0) // vertical gradient start
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.navigationController?.navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(#colorLiteral(red: 0.9579688907, green: 0.9579688907, blue: 0.9579688907, alpha: 1))]
}
You will probably have better results by subclassing UINavigationController:
class MyNavigationController: UINavigationController {
let gradient = CAGradientLayer()
override func viewDidLoad() {
super.viewDidLoad()
gradient.frame = navigationBar.bounds
gradient.colors = [ #colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1).cgColor, #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1).cgColor] // start color and end color
gradient.startPoint = CGPoint(x: 0.5, y: 0.0) // vertical gradient start
gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
if let image = getImageFrom(gradientLayer: gradient) {
navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
}
}
func getImageFrom(gradientLayer:CAGradientLayer) -> UIImage? {
var gradientImage:UIImage?
UIGraphicsBeginImageContext(gradientLayer.frame.size)
if let context = UIGraphicsGetCurrentContext() {
gradientLayer.render(in: context)
gradientImage = UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch)
}
UIGraphicsEndImageContext()
return gradientImage
}
}
Try calling:
DispatchQueue.main.async {
self.setNeedsStatusBarAppearanceUpdate()
}
after your setup is done. Should work without dispatching to main thread, but I had previously caught issues of things called from lifecycle methods not being on the main thread. So another thing to check is to make sure you are running the updates on the main thread.

UIBezierPath color change custom

I need to change the color of the UIBezierPath, but if I set a custom color, then there is simply no color.
UIColor(red: 255/255.0, green: 249/255.0, blue: 244/255.0, alpha: 1.0)
Tried adding colors via extension, but there is no color either.
UIColor.themeColor.setFill()
extension UIColor {
class var themeColor: UIColor {
return UIColor(red: 255/255.0, green: 249/255.0, blue: 244/255.0, alpha: 1.0)
}
}
Standard colors like .blue, .green, .red - work, but I need to understand how to set my own color through rgb
Here is my code
class MyView: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 303.19, height: 495.93))
path.stroke()
}
}
let views = MyView(frame: CGRect(x: 36.62, y: 77.54, width: 303.19, height: 495.93))
views.backgroundColor = .clear
views.rotate(radians: -45.84)
view.addSubview(views)
Use this if you want to change the color in UIBezierPath
path.fillColor = UIColor(red: 255/255.0, green: 249/255.0, blue: 244/255.0, alpha: 1.0).cgColor
path.fillColor = UIColor.red.cgColor
path.fillColor = UIColor(red: 155/255.0, green: 149/255.0, blue: 234/255.0, alpha: 1.0).cgColor
Works well

Gradient background iPhone dimensions on iPad

I have a problem setting gradient background on iPad. On iPhones everything is ok but when I use iPad the gradient background has iPhone dimensions.
The code that I use to make the gradient is the on below.
func setGradientToTableView(tableView: UITableView) {
let gradientBackgroundColors = [UIColor(red: 190.0/255.0, green: 219.0/255.0, blue: 0.0/255.0, alpha: 1).cgColor, UIColor(red: 13.0/255.0, green: 227.0/255.0, blue: 97.0/255.0, alpha: 1).cgColor]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = gradientBackgroundColors
gradientLayer.startPoint = CGPoint(x: 0,y: 0)
gradientLayer.frame = tableView.bounds
let backgroundView = UIView(frame: tableView.bounds)
backgroundView.layer.insertSublayer(gradientLayer, at: 0)
tableView.backgroundView = backgroundView
}
You need to set frame for layer in viewDidLayoutSubviews:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.backgroundView?.layer.sublayers?.forEach { $0.frame = tableView.bounds }
}
Also, as #Jan Schlorf suggests in comment, you can store your layer as property:
lazy var gradientLayer = CAGradientLayer()
//...
func setGradientToTableView(tableView: UITableView) {
let gradientBackgroundColors = [UIColor(red: 190.0/255.0, green: 219.0/255.0, blue: 0.0/255.0, alpha: 1).cgColor, UIColor(red: 13.0/255.0, green: 227.0/255.0, blue: 97.0/255.0, alpha: 1).cgColor]
gradientLayer.colors = gradientBackgroundColors
gradientLayer.startPoint = CGPoint(x: 0,y: 0)
gradientLayer.frame = tableView.bounds
let backgroundView = UIView(frame: tableView.bounds)
backgroundView.layer.insertSublayer(gradientLayer, at: 0)
tableView.backgroundView = backgroundView
}
//...
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradientLayer.frame = tableView.bounds
}
I assume you didn't use autolayout?
Check your tableviewsize when starting your app with iPad Simulator. I think it is not as big as you think it is.

Changing gradient background like in Instagram Log In

How to make changing gradient background like in Instagram Log In?
In Android you do it like this:
Is there a similar way to do it in Swift?
If you want to change continuously change view's background color with animation you can set it something like this.
var colors: [UIColor] = [.red, .blue, .green]
func startAnimation(index: Int) {
UIView.animate(withDuration: 2.5, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
self.view.backgroundColor = self.colors[index]
}) { (finished) in
var currentIndex = index + 1
if currentIndex == self.colors.count { currentIndex = 0 }
self.startAnimation(index: currentIndex)
}
}
And call this function with index 0.
self.startAnimation(index: 0)
In Swift3
Use CAGradientLayer with Using CABasicAnimation
I create PastelView Library to make alike instgram background animation effect
repo https://github.com/cruisediary/Pastel
Colors
var colors: [UIColor] = [UIColor(red: 156/255, green: 39/255, blue: 176/255, alpha: 1.0),
UIColor(red: 255/255, green: 64/255, blue: 129/255, alpha: 1.0),
UIColor(red: 123/255, green: 31/255, blue: 162/255, alpha: 1.0),
UIColor(red: 32/255, green: 76/255, blue: 255/255, alpha: 1.0),
UIColor(red: 32/255, green: 158/255, blue: 255/255, alpha: 1.0),
UIColor(red: 90/255, green: 120/255, blue: 127/255, alpha: 1.0),
UIColor(red: 58/255, green: 255/255, blue: 217/255, alpha: 1.0)]
Set Gradient
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = currentGradientSet()
gradient.startPoint = CGPoint(x:0, y:1)
gradient.endPoint = CGPoint(x:1, y:0)
gradient.drawsAsynchronously = true
layer.insertSublayer(gradient, at: 0)
Add Animation to gradient
let animation = CABasicAnimation(keyPath: Animation.keyPath)
animation.duration = animationDuration
animation.toValue = currentGradientSet()
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.delegate = self //this is important
gradient.add(animation, forKey: Animation.key)
After end animation loop another color set looping
extension PastelView: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
gradient.colors = currentGradientSet()
animateGradient()
}
}
}
Pastel should help you :)
You can do it pretty easily using CAGradientLayer:
let grad = CAGradientLayer()
grad.colors = [
UIColor.red.cgColor, // top color
UIColor.blue.cgColor // bottom color
]
grad.locations = [
0.0, // start gradating at top of view
1.0 // end gradating at bottom of view
]
grad.frame = view.bounds
view.layer.addSublayer(grad)
You could increase the first item in locations (0.0) to start the gradating further down, or you could decrease 1.0 to complete gradation higher up. It's a bit tough to explain, drop this into a playground and mess around a bit until you get your desired effect.
Example gradient and playground from the code above:
You can do like this in SWIFT 3. You can give more colors in it.
let gradient1 = CAGradientLayer()
gradient1.frame = CGRect(origin: CGPoint.zero , size: CGSize (width: self.view.frame.size.width,height: self.view.frame.size.height))
gradient1.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
print(gradient1.frame)
view_gradient.layer.masksToBounds = true
view_gradient.layer.addSublayer(gradient1)
Hope this works for you.

Swift: Adding gradient layer to button. Layer length error

let gradient: CAGradientLayer = CAGradientLayer()
let colorTop = UIColor(red: 112.0/255.0, green: 219.0/255.0, blue: 155.0/255.0, alpha: 1.0).CGColor
let colorBottom = UIColor(red: 86.0/255.0, green: 197.0/255.0, blue: 238.0/255.0, alpha: 1.0).CGColor
gradient.colors = [colorTop, colorBottom]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = loginButton.bounds
gradient.cornerRadius = 5
loginButton.layer.addSublayer(gradient)
The resulting gradient runs off goes beyond the button's frame. Why does this happen?
Probably you are setting gradient layer in viewDidLoad() or viewWillAppear(). At that time controller did not calculated views sizes. At time you add this sublayer button size was not calculated yet, so sublayer size is wrong. So you should fix next things:
First of all you should add gradient at viewDidAppear(), at this point all view's sizes are calculated.
Second, you should use layer.insertSublayer(layer, atIndex:index) instead of addSublayer(layer). Because in your case sublayer will hide buttons native layer (title, background...)
You should recalculate your sublayer size in viewDidLayoutSubviews(). Because when your button will change it's size (while rotating for example), sublayer will not change it's frame, so you should change it by yourself.
Add clipsToBounds and cornerRadius to loginbutton. That should fix the problem.
loginButton.clipsToBounds = true
loginButton.layer.cornerRadius = 5;
Is your Login Button's frame correct?It seems correct when I reproduce
let loginButton = UIButton(frame: CGRect(x: 10, y: 50, width: 300, height: 30))
self.view.addSubview(loginButton)
let gradient:CAGradientLayer = CAGradientLayer()
let colorTop = UIColor(red: 112.0/255.0, green: 219.0/255.0, blue: 155.0/255.0, alpha: 1.0).CGColor
let colorBottom = UIColor(red: 86.0/255.0, green: 197.0/255.0, blue: 238.0/255.0, alpha: 1.0).CGColor
gradient.colors = [colorTop, colorBottom]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = loginButton.bounds
gradient.cornerRadius = 5
loginButton.layer.addSublayer(gradient)
And it appear like below

Resources