简体   繁体   English

如何垂直对齐 textView 内的文本? (迅速)

[英]How to align text inside textView vertically? (Swift)

I found this which works perfectly on UITextViews linked to the viewController, but I can not figure out how to get it to work correctly for a UITextView created within a separate class.我发现这在链接到 viewController 的 UITextViews 上完美运行,但我无法弄清楚如何让它为在单独的类中创建的 UITextView 正常工作。

https://stackoverflow.com/a/41387780/8635708 https://stackoverflow.com/a/41387780/8635708

I want the view to be three units (character height) tall and the contents to be centered vertically.我希望视图高度为三个单位(字符高度),并且内容垂直居中。

This is what happens:这是发生的事情: 在此处输入图片说明

On the other hand, if I make the view 4 units tall, it looks good - but I don't have the space for that.另一方面,如果我将视图设置为 4 个单位高,它看起来不错 - 但我没有足够的空间。 在此处输入图片说明

Here is what I did (which seems to work for the single line).这是我所做的(这似乎适用于单行)。

class TestClass: UIView {

    var titleView1 = UITextView()
    var titleView2 = UITextView()

    override func layoutSubviews() {
        titleView1.centerVertically()
        titleView2.centerVertically()
    }


    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let h = 3 * GlobalConstants.fontSize // 3 * 14 = 42

        var title = "Single Line"
        var bounds = CGRect(x: 10, y: 10, width: 100, height: h)
        displayTitle(str: title, column: &titleView1, bounds: bounds)

        title = "First Line\nSecondLine"
        bounds = CGRect(x: 120, y: 10, width: 100, height: h)
        displayTitle(str: title, column: &titleView2, bounds: bounds)
    }


    func displayTitle(str: String, column: inout UITextView, bounds: CGRect) {
        
        let view = UITextView(frame: bounds)
        
        let attributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.blue,
            .font: UIFont.italicSystemFont(ofSize: 16)
        ]
        let attributedText = NSMutableAttributedString(string: str, attributes: attributes)

        view.attributedText = attributedText
        view.textAlignment = .center

        view.centerVertically()

        self.autoresizesSubviews = true
        self.addSubview(view)

    }

}

I don't believe vertical alignment can be done simply with an NSAttributedString but if possible, please let me know how!我不相信可以简单地使用NSAttributedString完成垂直对齐,但如果可能,请告诉我如何!

Thanks!谢谢!

I´m setting number of lines to 0 and using "\\n" to move Text up or down.我将行数设置为 0 并使用 "\\n" 向上或向下移动文本。

Very easy to use!非常容易使用!

"Single Line" + "\\n\\n\\n" to move the text up 3 lines "\\n\\n\\n" + "Single Line" to move the text down 3 lines "Single Line" + "\\n\\n\\n" 将文本向上移动 3 行 "\\n\\n\\n" + "Single Line" 将文本向下移动 3 行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM