【问题标题】:how to set textview height dynamically using autolayout如何使用自动布局动态设置文本视图高度
【发布时间】:2018-09-20 04:36:27
【问题描述】:

需要设置一个文本视图,其初始高度为 30 像这样

当用户输入文本时,文本视图的高度必须增加到一定高度

如何使用自动布局来实现这一点,这就是我的自动布局约束的样子

【问题讨论】:

  • 场景中的内容阻力和内容拥抱如何?您的问题与您在问题标题中的内容无关
  • 好的,那么有没有其他方法可以通过设置自动布局属性来实现这一点
  • 您可以拥有高度常数 IBOutlet 并根据 contnet 增加它,但小于您允许的最大尺寸
  • 你的身高是固定的。尝试删除高度并再次运行。
  • @MidhunNarayan 对我来说,它看起来比一切都简单。您必须获取文本的高度,然后使用 min(yourTextHeight,maximumHeight) 应用常量值。不相关,只是出于好奇您使用哪个库进行通话和视频通话

标签: ios swift autolayout textview storyboard


【解决方案1】:

试试这个

/// Orignal Height for Text View
var orignalHeight : CGFloat?

/// Height Constraint of Text View
@IBOutlet weak var descriptionTVHeightConstraint: NSLayoutConstraint!

/// In ViewDidLayoutSubviews Get Height
self.orignalHeight = self.descriptionTextView.frame.size.height

func textViewDidChange(_ textView: UITextView) {
        /// Get Width Which will be always same
        let fixedWidth = textView.frame.size.width

        /// Here we need to get The height as Greatest that we can have or expected
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

        /// Get New Size 
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

        /// New Frame
        var newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

        /// Orignal height is height that is assigned to TextView for first time and 100 is maximum height that textview can increase 
        self.descriptionTVHeightConstraint.constant = min(100,max(Int(newFrame.size.height),Int(self.orignalHeight!))



        bookSessionStruct.sessionTopicDiscussion = textView.text!.trimmed()

    }

【讨论】:

  • 在这段代码中,我会将最大高度设置为 100 吗?
  • 我建议不要在那里给出最大高度。让我们将其保留为最大的最佳幅度。但是如果上面还有其他最大高度,可以添加新的签入
  • @MidhunNarayan 检查编辑self.descriptionTVHeightConstraint.constant = min(100,max(Int(newFrame.size.height),Int(self.orignalHeight!)) 是你都需要的行!
【解决方案2】:

UITextViewisScrollEnabled 设置为false,然后UITextView 将自动适应它的大小。

并记住不要为具有恒定值的高度锚添加约束:

textView.snp.makeConstraints{ (maker) in maker.height.greaterThanOrEqualTo(xxx) }

希望对您有所帮助。

【讨论】:

  • 这个 snp 属性是什么,我需要导入什么才能得到这个?
  • 你应该导入SnapKit。我只想告诉你,如果你将isScrollEnabled 设置为false,那么你不应该为高度添加任何约束,因为它可以自动适应它的高度。
【解决方案3】:

UITextView 放入另一个容器视图(此处为红色)并设置容器视图的constraints,如下图所示。

containerview 中的UITextView 将有leading trailing top bottom 约束与containerview(红色)对齐。

之后,您必须获取容器视图的height 约束和bottom 约束的引用出口(下图)。

然后将下面显示的代码放入viewDilLoad方法中...

然后就写下这两个方法来控制剩下的事情。还有 Hola !你是冠军!你成功了。

//MARK: TextView delegate

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if(text == "\n") {
        textView.resignFirstResponder()
        return false
    }
    return true
}


func textViewDidChange(_ textView: UITextView) {


    let fixedWidth = textView.frame.size.width
    textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    var newFrame = textView.frame
    newFrame = CGRect.init(x: newFrame.origin.x, y: newFrame.origin.y+newFrame.height-newSize.height, width: max(newSize.width, fixedWidth), height: newSize.height)

    let newHeight = newFrame.size.height as CGFloat

    Swift.print("height: %f",newHeight)

    if newHeight > 40 && newHeight <= 105
    {
        chatBoxContainerViewHeightConstraint.constant = newHeight + 16
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }
    else if newHeight <= 40
    {
        chatBoxContainerViewHeightConstraint.constant = 56
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }

}


@objc func keyboardWillChangeFrame(_ notification: NSNotification) {

    if let userInfo = notification.userInfo {

        let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
        let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)

        let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let endFrameY = endFrame?.origin.y ?? 0
        let tabbarHeight = self.tabBarController?.tabBar.frame.size.height
        if (endFrameY >= UIScreen.main.bounds.size.height) {
            Swift.print("----< %f",endFrameY)
            self.bottomViewBottomConstraint.constant = 0
        } else  {
            Swift.print("----> %f",endFrameY)
            self.bottomViewBottomConstraint.constant = -((endFrame?.size.height)!-tabbarHeight! )
        }
        UIView.animate(withDuration: duration,
                       delay: TimeInterval(0),
                       options: animationCurve,
                       animations: { self.view.layoutIfNeeded() },
                       completion: nil)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 2018-02-22
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2016-04-25
    • 1970-01-01
    相关资源
    最近更新 更多