带有底部边框的自定义 UITextView

Custom UITextView with bottom border

我正在尝试创建自定义 UITextView class 以添加底部边框。使用以下代码,它不显示底部边框。我通过在情节提要中添加视图并根据需要对其进行操作来提供替代解决方案,但这不是最佳选择,因为我必须在许多地方使用 UITextView,因此我想要自定义 UITextView class。我有类似的自定义 UITextField 代码,它可以工作。

我还需要通过代码更改此边框的颜色。

有什么帮助吗?

import Foundation
import UIKit

class CustomTextView: UITextView {

    var bottomBorder = UIView()

    init(frame: CGRect) {
        super.init(frame: frame, textContainer: nil)
        self.initialize()
    }

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

    override func awakeFromNib() {
        super.awakeFromNib()
        self.initialize()

        // Setup Bottom-Border
        self.translatesAutoresizingMaskIntoConstraints = false

        bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        bottomBorder.backgroundColor = .red
        bottomBorder.translatesAutoresizingMaskIntoConstraints = false

        addSubview(bottomBorder)

        bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
        bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
        bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength
    }

    func initialize() {
    }

}

由于您所做的只是添加底部边框,因此您可以根据需要将其直接添加到 UITextView。您可以将其作为 InspectableVar 执行此操作,以便您可以在情节提要的属性选项卡中为每个文本视图设置它。

private var borders = [UITextView: Bool]()

extension UITextView {

  @IBInspectable var showBottomBorder: Bool {
    get {
      guard let b = borders[self] else {
        return true
      }
      return b
    }
    set {
      borders[self] = newValue
      setUpBottomBorder()
    }
  }

  func setUpBottomBorder(){
    let border = UIView()

    border.translatesAutoresizingMaskIntoConstraints = false
    border.backgroundColor = UIColor.red
    self.addSubview(border)

    border.heightAnchor.constraint(equalToConstant: 1).isActive = true
    border.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    border.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    border.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
  }
}

您必须在 superview 中添加 bottomBorder

所以用新的一行替换下面的行。

addSubview(bottomBorder)

self.superview!.addSubview(bottomBorder)

您将在文本视图中看到红色边框。