我正在尝试创建一个UITextView
,该文本可编辑但不可滚动并且垂直对齐。那是我现在的代码:
class MyTextView: UITextView {
public var verticalAlignment: UIControl.ContentVerticalAlignment = .center {
didSet {
let topCorrection: CGFloat
switch verticalAlignment {
case .center:
topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
case .bottom:
topCorrection = (bounds.size.height - contentSize.height * zoomScale)
case .top, .fill:
topCorrection = 0
@unknown default:
topCorrection = 0
}
contentInset.top = max(0, topCorrection)
}
}
}
问题是它在禁用滚动功能时不起作用。 您知道创建垂直对齐文本视图的其他方法吗?
PS:创建文本视图的代码:
let textView = MyTextView()
textView.backgroundColor = .clear
textView.attributedText = attributedString
textView.isUserInteractionEnabled = true
textView.isEditable = true
textView.allowsEditingTextAttributes = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero
textView.verticalAlignment = .bottom
textView.sizeToFit()
self.addSubview(textView)
答案 0 :(得分:0)
也许您打算使用UITextField?
let field = UITextField()
field.contentVerticalAlignment = UIControlContentVerticalAlignment.center
或将其设置为.bottom,.top等。
答案 1 :(得分:-1)
创建自定义textView
class CustomTextView: UITextView {
override var canBecomeFirstResponder: Bool {
return false
}
override var selectedTextRange: UITextRange? {
get {
return nil
} set {
}
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let tapGestureRecognizer = gestureRecognizer as? UITapGestureRecognizer,
tapGestureRecognizer.numberOfTapsRequired == 1 {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
if let longPressGestureRecognizer = gestureRecognizer as? UILongPressGestureRecognizer,
longPressGestureRecognizer.minimumPressDuration < 0.325 {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
gestureRecognizer.isEnabled = false
return false
}
}
将此文本视图用作文本视图的基类