如何将 TextView 高度动态更改为阈值,然后允许滚动? [英] How to change the TextView height dynamicly to a threshold and then allow scrolling?

查看:23
本文介绍了如何将 TextView 高度动态更改为阈值,然后允许滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最小高度为 33 的 TextView.从故事板中禁用了滚动.TextView 应根据内容增加高度,直到达到最大高度 100.然后我将 scrollEnabled 更改为 true,将 TextView 的高度更改为最大高度 100,但高度更改为 33.我该如何解决这个问题?

I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it reaches the max height of 100. Then I changes the scrollEnabled to true and the height of the TextView to max height of 100, but the height changes to the 33. How can I fix this problem?

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

@IBOutlet weak var messageTextView: UITextView!
let messageTextViewMaxHeight: CGFloat = 100

override func viewDidLoad() {
    super.viewDidLoad()
    self.messageTextView.delegate = self
}

func textViewDidChange(textView: UITextView) {

    if textView.frame.size.height >= self.messageTextViewMaxHeight {
        textView.scrollEnabled = true
        textView.frame.size.height = self.messageTextViewMaxHeight
    } else {
        textView.scrollEnabled = false
    }
}
}

推荐答案

看来您的代码需要进行两次更改,并且可以正常工作.

It seems your code requires two changes, and it will work fine.

  1. 提供 100 的最大高度而不是约束的最小高度:

  1. 更改代码如下:

  1. Change code as below:

 import UIKit

class ViewController: UIViewController, UITextViewDelegate
{
    @IBOutlet weak var messageTextView: UITextView!

    let messageTextViewMaxHeight: CGFloat = 100
    override func viewDidLoad()
    {
        super.viewDidLoad()
        messageTextView.delegate = self
    }

    func textViewDidChange(textView: UITextView)
    {
        if textView.contentSize.height >= self.messageTextViewMaxHeight
        {
            textView.scrollEnabled = true
        }
        else
            {
            textView.frame.size.height = textView.contentSize.height
            textView.scrollEnabled = false // textView.isScrollEnabled = false for swift 4.0
        }
    }
}

这篇关于如何将 TextView 高度动态更改为阈值,然后允许滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆