【问题标题】:How to draw a rectangle inside a tableviewcell如何在uitableviewcell内绘制一个矩形
【发布时间】:2016-01-18 18:45:04
【问题描述】:

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

【问题讨论】:

    标签: ios swift uitableview uikit core-graphics


    【解决方案1】:

    试试这个解决方案:

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

    【讨论】:

    • 那段代码应该放在哪里,Rashwan?在 UITableViewCell 子类或 UITableViewDataSource 函数之一或?
    • 添加到你的cellForRowAtIndexPath
    • 错误。 :-) 如果单元格被重用,那么每次调用cellForRowAtIndexPath 时,此代码将不断重新添加矩形子视图。最好在 UITableViewCell 子类的 viewDidLoad 方法中执行此操作,或者仅在第一次创建单元格时执行此操作。
    • 我不知道您想使用“重用”单元格,但请务必按​​照您在评论@MichaelDautermann 中提到的那样添加它。我刚刚更新了我的帖子,所以现在复制那里的代码。
    • 非常感谢您的回答,我会尝试并提供反馈
    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多