文本到UITextView的渐变颜色

问题描述 投票:-2回答:1

我需要像在instagram故事中那样将渐变色设置为带有白色背景色的UITextView。下面的示例:

enter image description here

swift uitextview
1个回答
1
投票

忽略以下代码中设置的约束,但概念应如下所示:

    containerView = GradientView.init()
    self.view.addSubview(containerView)
    containerView.translatesAutoresizingMaskIntoConstraints = false
    containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
    containerView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
    containerView.widthAnchor.constraint(equalToConstant: 220).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
    containerView.backgroundColor = .white

    textView = UITextView()
    containerView.addSubview(textView)
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 0).isActive = true
    textView.rightAnchor.constraint(equalTo: containerView.rightAnchor, constant: 0).isActive = true
    textView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0).isActive = true
    textView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0).isActive = true
    textView.text = "#SomeValue"
    textView.font = UIFont.systemFont(ofSize: 22, weight: .bold)
    containerView.layer.mask = textView.layer.sublayers?.last

其中GradientView是类似于:]的UIView子类>

class GradientView: UIView{





    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }


    func addGradient(){
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [UIColor.blue.cgColor,UIColor.red.cgColor,UIColor.green.cgColor]
        gradient.startPoint = CGPoint(x: 0, y: 1)
        gradient.endPoint = CGPoint(x: 1, y: 0)
        gradient.locations = [0,0.5,1]
        self.layer.addSublayer(gradient)
    }

}

enter image description here

应该看起来像这样。也许您的渐变颜色看起来会更好。

© www.soinside.com 2019 - 2024. All rights reserved.