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

4
我希望有一个可以多行输入文本的字段,它的外观像是一张有线纸,每一行条目下面都有一条横线,该横线应占据整个视图的宽度。
例如:example image这就是我想要的设计。行数可能会变化。
我考虑过以下两种方法:
  • 使用UITextView并放置一个线条背景。
  • 使用TextField并为每个TextField加下划线。
然而,我认为这些都不太可行,所以我正在寻找其他点子,能够指导我朝着正确的方向前进。

TableView怎么样? - Amanpreet
听起来好像使用TableView可能是个不错的选择。您希望用户能够直接编辑文本吗? - Benjamin Lowry
@Amanpreet 这是一个UITableView的单元格。 - rv7284
啊,是的,那么一个表格视图将不起作用。 - Benjamin Lowry
您可以像这样放置UITextFields,只有底部边框。并禁用除第一个文本字段以外的所有其他文本字段。当用户按下返回键或文本字段中的文本到达字段末尾时,才启用下一个文本字段。 - KAR
显示剩余3条评论
2个回答

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

谢谢,伙计。我一定会尝试这个的。 - rv7284
为了设置正确的颜色,在这个例子中是白色,在以下代码行后:let ctx = UIGraphicsGetCurrentContext(),插入以下代码:ctx?.setStrokeColor(UIColor.white.cgColor)。 - Andrea Leganza
注意:此代码不会滚动行,因此应进行修改以获得正确的行为。 - Andrea Leganza
@AndreaLeganza 你更新了支持滚动的代码了吗? - Akhil K C
@AkhilKC 不好意思,我没有时间编写和修复它,所以我采取了另一种方式。 - Andrea Leganza
@AndreaLeganza,您能提供您的解决方案吗? - Brandon512

-1
添加TextView代理,然后在确认为UITextViewDelegate代理后使用。
 func scrollViewDidScroll(_ scrollView: UIScrollView) {
      yourTextView.setNeedsDisplay()
}

希望能有所帮助!

这并没有试图回答问题。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接