ios - 如何在 uitableviewcell 内绘制一个矩形

标签 ios swift uitableview uikit core-graphics

可能这是一个奇怪的问题,但我放弃了。情况:我有一个带有原型(prototype)单元格的 TableView。在单元格内(我有一个自定义类)我想要一个背景,但不是整个单元格,以及一个标签。当我知道文本的长度时,背景的大小就会改变。背景是一个矩形,渐变填充,圆角半径,渐变填充。我应该如何绘制这个矩形?我应该用 UIKit 还是用 CoreGraphics 来做?我的第一个想法是导入图像,但因为如果有长文本我必须将其放大,所以我决定以编程方式进行。提前致谢。

最佳答案

试试这个解决方案:

// 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)

关于ios - 如何在 uitableviewcell 内绘制一个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34861858/

相关文章:

ios - 在 iOS 中使用 Parse 调用 findObjectsInBackGroundWithBlock() 时出现问题

iphone - tableview 背景颜色不正确,错误的颜色漂浮在单元格后面

ios - 在函数内将数据传递到 segue.destination 时出现问题

ios - 多点连接减缓 View 创建

ios - 在 UITableView 集合上水平滚动

ios - 从带有搜索栏的 TableView Controller 移动到 UISearchDisplayController

ios - 章节标题困惑

iphone - 将手机的照片复制到应用程序的目录

ios - 我的模型对象是否应该负责下载它们自己的资源?

ios - 从侧面菜单中选择项目时打开特定的 ViewController?