【问题标题】:Vertical alignment on editable UITextView可编辑 UITextView 上的垂直对齐
【发布时间】:2019-10-12 19:02:14
【问题描述】:

我想在我的UITextView 上设置垂直对齐。文本视图是可编辑的并且滚动被禁用:

let textView = UITextView(frame: frame)
textView.backgroundColor = .clear
textView.attributedText = myAttributedString
textView.isUserInteractionEnabled = true
textView.isEditable = true
textView.allowsEditingTextAttributes = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero
self.addSubview(textView)

所以,我想做类似的事情:

textView.verticalAlignment = .center

我已经尝试子类化文本视图并添加如下属性:

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

但它似乎不适用于将isScrollEnabled 设置为false

我在互联网上找到的所有其他解决方案也都不起作用,我有点绝望……你能帮帮我吗?

谢谢

【问题讨论】:

    标签: ios swift alignment uitextview vertical-alignment


    【解决方案1】:

    创建自定义文本视图

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

    将此文本视图用作文本视图的基类

    【讨论】:

    • 它应该如何回答我的问题?
    【解决方案2】:

    也许您打算使用 UITextField?

    let field = UITextField()
    field.contentVerticalAlignment = UIControlContentVerticalAlignment.center
    

    或将其设置为 .bottom、.top 等。

    【讨论】:

    • 谢谢!但是UITextField 只是一行……
    猜你喜欢
    • 1970-01-01
    • 2013-04-26
    • 2013-10-28
    • 2013-06-06
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多