【问题标题】:Adding gradient to UILabel through extension通过扩展向 UILabel 添加渐变
【发布时间】:2021-10-18 01:52:53
【问题描述】:

您可能知道,如果您尝试为 UILabel 设置渐变背景,它会覆盖文本。 我想为 UILabels 编写一个扩展,以便放置渐变背景。 这是我的代码,但渐变放在一个正方形中,向下和向右移动到标签。我不明白为什么,因为我使用的是同一个框架

public extension UILabel {
    func applyGradientToLabelAtAngle(_ angle : CGFloat, _ color1 : UIColor, _ color2 : UIColor){
        let gradient = CAGradientLayer()
        gradient.frame = self.frame
        gradient.colors = [color1.cgColor, color2.cgColor]
        gradient.calculatePoints(for: angle)
        let index = self.layer.superlayer!.sublayers!.firstIndex(of: self.layer)!
        self.layer.superlayer!.sublayers!.insert(gradient, at: index)
        
    }
}

编辑:calculatePoints 函数计算位置,对问题不重要

【问题讨论】:

    标签: ios swift user-interface gradient


    【解决方案1】:

    信息不足。当我这样称呼你的代码时,你的代码对我来说很好:

        let lab = UILabel()
        lab.text = "Howdy there"
        lab.sizeToFit()
        lab.frame.origin = .init(x:100, y:100)
        self.view.addSubview(lab)
        lab.applyGradientToLabelAtAngle(.pi, .green, .red)
    

    问题显然是你没有这样称呼它。但是你没有说你是怎么称呼它的。我怀疑您在错误的时间调用它,即在最重要的self.frame 尚不为人所知的时候。

    【讨论】:

    • 谢谢,我只好在viewDidLayoutSubviews中调用了
    • 是的,这是正确的地方。但小心点。这种方法被调用了很多,所以你最终会得到很多渐变层。
    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多