i hava a problem, i am tryinf to set background color to label, but it is not working
This is how i set label
private var imageLbel: UILabel = {
let label = UILabel()
label.textColor = .white
label.font = UIFont(name: "Arial Rounded MT Bold", size: 25)
label.textAlignment = .center
label.backgroundColor = GradientColor.setGradient()
label.numberOfLines = 1
return label
}()
This is class for gradient
class GradientColor {
static func setGradient(uiView: UIView) -> UIColor {
let colorTop = UIColor.orange
let colorBottom = UIColor.systemOrange
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.frame = uiView.bounds
uiView.layer.insertSublayer(gradientLayer, at: 0)
return gradientLayer
}
}
The backgroundColor property accepts a value of type UIColor to be assigned, but your implementation of the function setGradient(uiView:) is not returning a value with the correct type. Also, you are calling setGradient() without passing the uiView argument required. I don't think your code even compiles correctly.
The function setGradient(uiView:) appears to be creating a CAGradientLayer instance and inserting it as a sublayer of the input uiView. I do not think returning a UIColor is required.
I suggest removing the line label.backgroundColor = GradientColor.setGradient(). Then, remove -> UIColor from the signature of setGradient(uiView:) so that it doesn't return anything, and remove return gradientLayer.
After that, somewhere after the label is added to the view hierarchy, call setGradient(uiView:) passing it imageLbel. Maybe in viewDidLoad() like this:
override viewDidLoad() {
super.viewDidLoad()
GradientColor.setGradient(uiView: imageLbel)
}
Related
I use SnapKit in my project and trying to add gradient on my button
I have extension:
extension UIButton {
public func setGradientColor(colorOne: UIColor, colorTwo: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
layer.insertSublayer(gradientLayer, at: 0)
}
}
i have button config where i am trying to use gradient:
private var playersButton: UIButton = {
let button = UIButton(type: .custom)
button.setGradientColor(colorOne: .red, colorTwo: .blue)
button.frame = button.layer.frame
return button
}()
and SnapKit here
playersButton.snp.makeConstraints { make in
make.leading.equalToSuperview().inset(60)
make.trailing.equalToSuperview().inset(60)
make.bottom.equalTo(startGameButton).inset(100)
make.height.equalTo(screenHeight/12.82)
}
The problem is i have not result of it, i dont see gradientm but if i delete snapKit config and will use setGradient extension in viewDidLoad it works well!
Example:
private var playersButton: UIButton = {
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
playersButton.setGradientColor(colorOne: .blue, colorTwo: .red)
}
How do i change my code to use first method? Thank you
The difference is that when using SnapKit you're using Auto-Layout, so your button's frame is not set when you call button.setGradientColor(colorOne: .red, colorTwo: .blue).
The result is that your gradient layer ends up with a frame size of Zero - so you don't see it.
You will likely find it much easier and more reliable to use a button subclass like this (simple example based on the code you posted):
class MyGradientButton: UIButton {
let gradLayer = CAGradientLayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
layer.insertSublayer(gradLayer, at: 0)
}
public func setGradientColor(colorOne: UIColor, colorTwo: UIColor) {
gradLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradLayer.locations = [0.0, 1.0]
gradLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
}
override func layoutSubviews() {
super.layoutSubviews()
gradLayer.frame = bounds
}
}
Then change your button declaration to:
private var playersButton: MyGradientButton = {
let button = MyGradientButton()
button.setGradientColor(colorOne: .red, colorTwo: .blue)
return button
}()
Now, whether you set its frame explicitly, or if you use auto-layout (normal syntax or with SnapKit), the gradient layer will automatically adjust whenever the button's frame changes.
As you can see in the image, the UITextField (only on tvOS?) by default has these behaviors:
A translucent overlay (make the background and the white text grey in the second button)
A white background and bigger size when it's focused (the first button)
How do I remove/change these behaviors?
What did I do?
I tried to change all color related property (except text color) in Interface Builder to Clear color
I used these code to build the view programmatically
let view = UITextField()
view.backgroundColor = .clear
view.translatesAutoresizingMaskIntoConstraints = false
view.font = view.font?.withSize(16)
view.textAlignment = .center
view.borderStyle = .none
view.tintColor = .clear
view.tintAdjustmentMode = .normal
view.accessibilityIgnoresInvertColors = true
view.textColor = .white
view.disabledBackground = .none
view.background = .none
view.layer.backgroundColor = CGColor(gray: 0.0, alpha: 0.0)
view.layer.shadowColor = CGColor(gray: 0.0, alpha: 0.0)
view.layer.borderColor = CGColor(gray: 0.0, alpha: 0.0)
view.layer.shadowOpacity = 0.0
Additional Information
A new tvOS app project, created with XCode 12.2 in macOS 10.15.7
Run on Apple TV simulator
No additional libraries/pods used
Actually we always can inherit UIKit classes and do whatever layout/style we want. Here is very raw demo of how this can be done.
Prepared & tested with Xcode 12.1 / tvOS 14.0
So just substitute custom subclass of UITextField class
class MyTextField: UITextField {
lazy var textLayer = CATextLayer()
override func didMoveToSuperview() {
super.didMoveToSuperview()
layer.backgroundColor = UIColor.clear.cgColor
textLayer.font = self.font
textLayer.fontSize = 36
textLayer.foregroundColor = UIColor.white.cgColor
textLayer.alignmentMode = .center
textLayer.frame = layer.bounds
layer.addSublayer(textLayer)
layer.borderWidth = 2
}
override func layoutSublayers(of layer: CALayer) {
layer.borderColor = self.isFocused ? UIColor.black.cgColor : UIColor.clear.cgColor
textLayer.frame = layer.bounds
textLayer.string = self.text?.isEmpty ?? true ? self.placeholder : self.text
}
override func addSubview(_ view: UIView) {
// blocks standard styling
}
}
I have created a messaging app and I want to set the border colour as a gradient instead of just a solid colour.
So far when I run my code this is what is see:
The gradient colour is supposed to be a border colour for each message cell
I don't know what is making it look the way it does
this is how I coded it :
I've created an extension to deal with the gradient and it looks like this:
extension UIView {
func gradientButton( startColor:UIColor, endColor:UIColor) {
let view:UIView = UIView(frame: self.bounds)
let gradient = CAGradientLayer()
gradient.colors = [startColor.cgColor, endColor.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = self.bounds
self.layer.insertSublayer(gradient, at: 0)
self.mask = view
view.layer.borderWidth = 2
}
}
and when I set the gradient I set it like this in my chatController class
class ChatController: UICollectionViewController, UICollectionViewDelegateFlowLayout, ChatCellSettingsDelegate {
func configureMessage(cell: ChatCell, message: Message) {
cell.bubbleView.gradientButton(startColor: blue, endColor: green)
}
The bubbleView holds the text which is a textView of the message which is created in my ChatCell class:
class ChatCell: UICollectionViewCell {
let bubbleView: UIView = {
let bubble = UIView()
bubble.backgroundColor = UIColor.rgb(red: 0, green: 171, blue: 154, alpha: 1)
bubble.translatesAutoresizingMaskIntoConstraints = false
bubble.layer.masksToBounds = true
bubble.layer.cornerRadius = 13
bubble.backgroundColor = .white
return bubble
}()
let textView: UITextView = {
let text = UITextView()
text.text = "test"
text.font = UIFont.systemFont(ofSize: 16)
text.backgroundColor = .clear
text.translatesAutoresizingMaskIntoConstraints = false
text.isEditable = false
return text
}()
}
how do I fix this?
any help would be helpful
thank you
I can set the border colour to a solid colour with the following line:
cell.bubbleView.layer.borderColor = UIColor.rgb(red: 91, green: 184, blue: 153, alpha: 0.8).cgColor
and then it would look like this:
You can create your own bordered view and use it in your custom cell:
import UIKit
import PlaygroundSupport
public class GradientBorder: UIView {
var startColor: UIColor = .black
var endColor: UIColor = .white
var startLocation: Double = 0.05
var endLocation: Double = 0.95
var path: UIBezierPath!
let shape = CAShapeLayer()
var lineWidth: CGFloat = 5
override public class var layerClass: AnyClass { CAGradientLayer.self }
var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }
func update() {
gradientLayer.startPoint = .init(x: 0.0, y: 0.5)
gradientLayer.endPoint = .init(x: 1.0, y: 0.5)
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
path = .init(roundedRect: bounds.insetBy(dx: lineWidth/2, dy: lineWidth/2), byRoundingCorners: [.topLeft, .bottomLeft, .topRight, .bottomRight], cornerRadii: CGSize(width: frame.size.height / 2, height: frame.size.height / 2))
shape.lineWidth = lineWidth
shape.path = path.cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradientLayer.mask = shape
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
update()
}
}
Playground testing:
let gradientBorderedView = GradientBorder()
gradientBorderedView.frame = .init(origin: .zero, size: .init(width: 200, height: 40))
let view = UIView()
view.frame = .init(origin: .zero, size: .init(width: 375, height: 812))
view.backgroundColor = .blue
view.addSubview(gradientBorderedView)
PlaygroundPage.current.liveView = view
I have the following parts:
- My main view is a UIViewController with a UICollectionView
- The cell for the UICollectionView
- A subclass of the UIView to build a CAShapeLayer with an CABasicAnimation
In my main view I have a UICollectionView which renders a bunch of cells with labels etc. It also is showing a progress graph.
In my subclass ProgressCirclePath() I am drawing a CAShapeLayer which is acting as the progress graph rendered in each cell of my UICollectionView.
I have been able to pass data to each cell, e.g. the labels as well as the CAShapeLayer strokeEnd values.
Everything is fine until I try to add a CABasicAnimation to my path. In this case I am not able to set the value for the animations toValue. Testing using the print console reveals that the value is available in my UICollectionView but not in the animation block in my subClass (which is where it simply returns nil). I have tried simply setting the toValue as well as creating a variable within my ProgressCirlePath and setting it from the UICollectionView. Neither worked.
I'd appreciate any hints on why this is happening and how to solve this. Thanks!!
Within my UICollectionView:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = decksCollectionView.dequeueReusableCell(withReuseIdentifier: "DeckCell", for: indexPath) as! DeckCell
cell.creatorLabel.text = deckCellCreator[indexPath.item]
cell.titleLabel.text = deckCellTitle[indexPath.item]
cell.progressLabel.text = "\(deckCellCompletionPercentage[indexPath.item])%"
cell.progressGraphView.animation.toValue = CGFloat(deckCellCompletionPercentage[indexPath.item])/100
return cell
}
The setup within my cell class:
let progressGraphView: ProgressCirclePath = {
let circlePath = ProgressCirclePath(frame: CGRect(x:0, y:0, width: 86, height: 86))
circlePath.progressLayer.position = circlePath.center
circlePath.progressBackgroundLayer.position = circlePath.center
circlePath.translatesAutoresizingMaskIntoConstraints = false
return circlePath
}()
And here my ProgressCirclePath()
class ProgressCirclePath: UIView {
let progressLayer = CAShapeLayer()
let progressBackgroundLayer = CAShapeLayer()
let animation = CABasicAnimation(keyPath: "strokeEnd")
// var percentageValue = CGFloat()
override init(frame: CGRect) {
super.init(frame: frame)
layer.addSublayer(progressBackgroundLayer)
layer.addSublayer(progressLayer)
let circularPath = UIBezierPath(arcCenter: .zero, radius: 43, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true)
progressBackgroundLayer.path = circularPath.cgPath
progressBackgroundLayer.lineWidth = 10
progressBackgroundLayer.strokeStart = 0
progressBackgroundLayer.strokeEnd = 1
progressBackgroundLayer.strokeColor = UIColor(red: 221/255.0, green: 240/255.0, blue: 226/255.0, alpha: 1.0).cgColor
progressBackgroundLayer.fillColor = UIColor.clear.cgColor
progressBackgroundLayer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)
progressLayer.path = circularPath.cgPath
progressLayer.lineWidth = 10
progressLayer.lineCap = kCALineCapRound
progressLayer.strokeColor = UIColor(red: 72/255.0, green: 172/255.0, blue: 104/255.0, alpha: 1.0).cgColor
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)
animation.duration = 1
animation.fromValue = 0
// animation.toValue = percentageValue
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
progressLayer.add(animation, forKey: "animateGraph")
print("animation.toValue \(animation.toValue)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("has not been implemented")
}
}
You're handling the injection of data and animation too early in the lifecycle of the custom view. Instead of handling them in the object's initializer, move them to a later and more appropriate method, such as layoutSubviews:
override open func layoutSubviews() {
super.layoutSubviews()
// handle post-init stuff here, like animations and passing in data
// when it doesn't get passed in on init
}
Trying to show the progress bar made it custom, took an UIView set it frame to percent of progress. Say 20% of frame width and made gradient but remaining 80% should be white color and text on it defining percentage.
Problems facing is not able to display text set UILabel instead of UIView but text not displaying. Please guide.
Below is what i have tried.
let view: UILabel = UILabel(frame: CGRectMake(0.0, self.scrollMainView.frame.size.height-50, self.view.frame.size.width/5, 50))
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = view.bounds
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
let color0 = UIColor(red:71.0/255, green:198.0/255, blue:134.0/255, alpha:1.0).CGColor
let color1 = UIColor(red:25.0/255, green:190.0/255, blue: 205.0/255, alpha:1.0).CGColor
// let color2 = UIColor(red:0.0/255, green:0.0/255, blue: 0.0/255, alpha:1.0).CGColor
gradient.colors = [color1, color0]
view.layer.insertSublayer(gradient, atIndex: 0)
self.scrollMainView.addSubview(view)
view.text = "20%"
view.textColor = UIColor.blackColor()
view.layer.shadowColor = UIColor.blackColor().CGColor
view.layer.shadowOpacity = 1
view.layer.shadowOffset = CGSizeZero
view.layer.shadowRadius = 2
I cant understand your problem from your question exactly but I will answer based on question title only. To get half color gradient and half single color you have to use three colors gradient and set their locations accordingly :
gradient.colors = [color1,color1, color0]
gradient.locations = [0.0, 0.5, 1.0]
This way you will draw a gradient from color1 to color1 (which in fact is single color) and fill 50% of frame's area with it and a gradient from color1 to color0 that will fill other half of the frame.
I answer to why you can't see the text.
Forget for one second layers and think about subviews. What should happen if you add a subview to a UILabel? It will be on top of the label's content, of course.
So, the same applies to layers. The UILabel draws its text on its main layer, and any sublayer you add to the main layer is on top of it.
My suggestion is to use a UIView with a CAGradientLayer sublayer and a UILabel subview.
Or even better, subclass a UIView in order to use a CAGradientLayer as backing layer (through class func layerClass() -> AnyClass method) and just add UILabel as subview.
Here is an example:
class CustomView : UIView {
lazy var label : UILabel = {
let l = UILabel(frame: self.bounds)
l.text = "20%"
l.textColor = UIColor.blackColor()
l.backgroundColor = UIColor.clearColor()
return l
}()
override class func layerClass() -> AnyClass {
return CAGradientLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
let gradient: CAGradientLayer = self.layer as! CAGradientLayer
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
let color0 = UIColor(red:71.0/255, green:198.0/255, blue:134.0/255, alpha:1.0).CGColor
let color1 = UIColor(red:25.0/255, green:190.0/255, blue: 205.0/255, alpha:1.0).CGColor
gradient.colors = [color1, color0]
label.frame = bounds
label.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.addSubview(label)
}
}