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

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

问题描述

我有一个TextView,其最小高度限制为33.滚动是从情节提要中禁用的. 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天全站免登陆