如何根据文本视图内容大小设置滚动视图中的启用或禁用滚动?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何根据文本视图内容大小设置滚动视图中的启用或禁用滚动?相关的知识,希望对你有一定的参考价值。

enter image description here

我正在尝试创建一个具有滚动视图和文本视图的视图控制器。我希望仅当文本视图的文本内容很多时才启用滚动。因为如果我可以滚动我的视图控制器看起来很难看,即使文本视图中的文本内容与下图不太相似

enter image description here

我们可以看到视图控制器底部存在很大差距。这是我用于此VC的代码

import UIKit

class NotificationDetailVC: UIViewController {

    @IBOutlet weak var notificationTitleLabel: UILabel!
    @IBOutlet weak var notificationImage: UIImageView!
    @IBOutlet weak var notificationDateLabel: UILabel!
    @IBOutlet weak var notificationContentTextView: UITextView!

    var dataNotification : [String:Any]?

    override func viewDidLoad() {
        super.viewDidLoad()
        updateUI()
        updateReadStatusInUserDefault()
    }

    @IBAction func imageDidTapped(_ sender: Any) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let popup = storyboard.instantiateViewController(withIdentifier: "imageDisplay") as! ReusableImageDisplayVC
        popup.photo = notificationImage.image
        self.present(popup, animated: true, completion: nil)
    }

    func updateUI() {
        guard let dataNotification = dataNotification else {return}
        notificationTitleLabel.text = dataNotification["Judul"] as? String
        notificationContentTextView.text = dataNotification["Keterangan"] as? String

        guard let notifDate = dataNotification["TglNotif"] as? String else {return}
        notificationDateLabel.text = DateTimeService.changeFormat(of: notifDate, toFormat: "d MMM YYY")

        let imagePath = dataNotification["Photo"] as? String
        guard let encodedImagePath = imagePath?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else {return}

        if imagePath != nil {
            if imagePath!.isEmpty {
                notificationImage.removeFromSuperview()
            } else {
                notificationImage.sd_setImage(with: URL(string: encodedImagePath), placeholderImage: UIImage(named: "3-2 Img"), options: [.continueInBackground, .progressiveDownload])
            }
        } else {
            notificationImage.removeFromSuperview()
        }
    }

    func updateReadStatusInUserDefault() {
        guard let dataNotification = dataNotification,
            let notifID = dataNotification["notif_id"] as? Int else {return}

        guard var readNotificationStatusUserDefault  = UserDefaults.standard.object(forKey: "readNotification") as? [String:String] else {return}

        readNotificationStatusUserDefault["(notifID)"] = "1"
        UserDefaults.standard.set(readNotificationStatusUserDefault, forKey: "readNotification")
        UserDefaults.standard.synchronize()
    }
}
答案

首先,您需要查找textview文本的大小,您可以使用以下方法查找文本大小:

func rectForText(text: String, font: UIFont, maxSize: CGSize) -> CGSize
{
    let attrString = NSAttributedString.init(string: yourtext, attributes: [NSAttributedStringKey.font:font])
    let rect = attrString.boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
    let size = CGSize(width: rect.size.width, height: rect.size.height)//(, )
    return size
}

根据您的文字大小设置textview的大小后:

let contentSize : CGSize = rectForText(text: str, font:UIFont.boldSystemFont(ofSize: 15.0) , maxSize : CGSize(width: 200 * (SCREEN_WIDTH / 320), height: 20000) )

并设置textview的框架

var frame = self.myTextView.frame
frame.size.height = contentSize.height
self.myTextView.frame = frame

在设置了scrollview的内容后

scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: myTextView.frame.size.height + 8)

希望这有帮助!快乐编码:)

另一答案

根据文本视图的contentSize,调整滚动视图的可滚动属性。

在textview上设置文本后,请检查如下: -

    let height = self.notificationContentTextView.contentSize.height
if(height > scrollView.frame.size.height){
scrollView.isScrollEnabled == true
}else{
scrollView.isScrollEnabled == false
}

以上是关于如何根据文本视图内容大小设置滚动视图中的启用或禁用滚动?的主要内容,如果未能解决你的问题,请参考以下文章

在 UIScrollView 中自动调整 UITextView 的大小

使用 CSS 禁用文本框

Android:一旦我以编程方式禁用滚动视图行为,我将无法再次启用它

Xcode UIScrollView 布局 - 设置水平内容大小并水平调整子视图大小

如何使用自动布局设置滚动视图内容大小?

如何根据动态内容调整 textview 和 scrollview 内容大小