Underline text in a UITextView

前端 未结 13 1402
情歌与酒
情歌与酒 2020-12-14 23:37

How can I underline text in a UITextView. I understand that I would need to create a subclass of UITextView, but what would go under drawRect

13条回答
  •  执笔经年
    2020-12-14 23:57

    Swift 5. As my UITextView if for inserting text, I created an extension function as bellow.

    extension UITextView {
    
      func underlined() {
        let border = CALayer()
        let width = CGFloat(1.0)
        border.borderColor = UIColor.lightGray.cgColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - 5, width:  self.frame.size.width, height: 1)
        border.borderWidth = width
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
        let style = NSMutableParagraphStyle()
        style.lineSpacing = 15
        let attributes = [NSAttributedString.Key.paragraphStyle : style, NSAttributedString.Key.foregroundColor : UIColor.darkGray, NSAttributedString.Key.font :  UIFont.systemFont(ofSize: 13)]
        self.attributedText = NSAttributedString(string: self.text, attributes: attributes)
      }
    
    }
    

    The border is drawling the line and the style is adding the spacing between the lines. Usage in your UIView custom layout:

    override func layoutSubviews() {
        super.layoutSubviews()
        self.dateAndTimeInput.underlined()
      }
    

    Image with the result

提交回复
热议问题