如何制作多行、下划线的UITextView/UITextField?

rv7*_*284 4 iphone ios swift

我想要一个具有横格纸外观的多行文本输入字段,其中每个输入行下方都有一条下划线,文本将跨越视图的宽度。

例如: 示例图像

这就是我想做的设计。行数可能会改变。

我考虑过:

  • 使用 UITextView 并放置线条背景。
  • 使用文本字段并为每个文本字段添加下划线。

这些对我来说听起来都不合理,所以我正在寻找其他可以让我指明正确方向的想法。

Vik*_*mkó 6

您可以使用 CoreGraphics 绘制线条:

class UnderlinedTextView: UITextView {
  var lineHeight: CGFloat = 13.8

  override var font: UIFont? {
    didSet {
      if let newFont = font {
        lineHeight = newFont.lineHeight
      }
    }
  }

  override func draw(_ rect: CGRect) {
    let ctx = UIGraphicsGetCurrentContext()
    ctx?.setStrokeColor(UIColor.black.cgColor)
    let numberOfLines = Int(rect.height / lineHeight)
    let topInset = textContainerInset.top

    for i in 1...numberOfLines {
      let y = topInset + CGFloat(i) * lineHeight

      let line = CGMutablePath()
      line.move(to: CGPoint(x: 0.0, y: y))
      line.addLine(to: CGPoint(x: rect.width, y: y))
      ctx?.addPath(line)
    }

    ctx?.strokePath()

    super.draw(rect)
  }
}
Run Code Online (Sandbox Code Playgroud)