Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a rectangle inside a tableviewcell

Probably it's a weird question, but I gave up. Situation: I have a TableView with a prototype cell. Inside the cell (I have a custom class) I want to have a background, but not the whole cell, and a label on it. The size of the background would be changed when I know the length of the text. The background is a rectangle, with a gradient fill, corner radius, gradient fill. How should I draw this rect? Should I do it with UIKit or with CoreGraphics? My first thought was to import the image but because i have to make it bigger if there is a long text, I decided to make it programmaticaly. Thanks in advance.

like image 542
schoeberlt Avatar asked May 10 '26 03:05

schoeberlt


1 Answers

Try this solution:

// Add a label with sizeToFit
let label = UILabel()
label.text = "Add some text that you want"
label.sizeToFit()

// Add a rectangle view
let rectangle = UIView(frame: CGRect(x: 0, y: 0, width: label.frame.size.width, height: 40))

// Add gradient
let gradientLayer = CAGradientLayer()
gradientLayer.frame = rectangle.bounds

let color1 = UIColor.yellowColor().CGColor as CGColorRef
let color2 = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0).CGColor as CGColorRef
let color3 = UIColor.clearColor().CGColor as CGColorRef
let color4 = UIColor(white: 0.0, alpha: 0.7).CGColor as CGColorRef

gradientLayer.colors = [color1, color2, color3, color4]
gradientLayer.locations = [0.0, 0.25, 0.75, 1.0]
rectangle.layer.addSublayer(gradientLayer)

// Add corner radius
gradientLayer.cornerRadius = 10

// Add the label to your rectangle
rectangle.addSubview(label)

// Add the rectangle to your cell
cell.addSubview(rectangle)
like image 118
Rashwan L Avatar answered May 11 '26 23:05

Rashwan L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!