如何让文本在UITextView中与顶部对齐?

时间:2017-09-14 03:02:08

标签: ios swift uitextview

运行Xcode 8.3.3我有一个UITextView填充整个视图。但是,文本没有与顶部对齐,但在顶部有超过80个点填充 - 请参见随附的屏幕截图。

我使用了约束,对齐和搜索文档但无法看到如何解决此问题。

任何指针都会受到赞赏。

enter image description here

3 个答案:

答案 0 :(得分:0)

好的,根据您的查询我尝试了一个解决方案,请看看这个

1)这是第一个带空格的输出,默认情况下

我使用下面的代码来显示实际发生的事情,我正在使用一个textView,从上到下覆盖我的全屏幕从故事板

 //Outlet
 @IBOutlet weak var myTextView: UITextView!

 //call the function and assign to TextView
 override func viewWillAppear(_ animated: Bool) {
        adjustContentSize(tv: myTextView)
    }

    //this will Add the respected boundaries to textView content 
    func adjustContentSize(tv: UITextView){
        let deadSpace = tv.bounds.size.height - tv.contentSize.height
        let inset = max(0, deadSpace/2.0)

        tv.contentInset = UIEdgeInsetsMake(inset, tv.contentInset.left, inset, tv.contentInset.right)
    }

    //Will check when value is changed
    func textViewDidChange(_ textView: UITextView) {
        self.adjustContentSize(tv: textView)
    }

- 模拟器输出

enter image description here

2)按预期输出

- 代码

//Outlet
 @IBOutlet weak var myTextView: UITextView!

 //call the function and assign to TextView
 override func viewWillAppear(_ animated: Bool) {
        adjustContentSize(tv: myTextView)
    }

//this will Add the respected boundaries to textView content 
    func adjustContentSize(tv: UITextView){
        tv.contentInset = UIEdgeInsetsMake(0, tv.contentInset.left, 0,tv.contentInset.right)
    }

    //Will check when value is changed
    func textViewDidChange(_ textView: UITextView) {
        self.adjustContentSize(tv: textView)
    }

- 预期产出

enter image description here

希望它能帮助你:)

答案 1 :(得分:0)

问题与自动布局有关。如果您查看问题中textView屏幕截图的位置,您可以看到textView相对于导航栏而不是View定位。通过向上移动顶部位置(请参见下面的屏幕截图),文本对齐问题已得到解决。enter image description here

答案 2 :(得分:0)

使用textContainerInset将文本与textView顶部对齐 textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

如果只想更改顶部插图,则可以使用现有textContainerInset中的左侧,底部和右侧插图。