gpt4 book ai didi

ios - 光标在 UITextView 中的奇怪定位

转载 作者:搜寻专家 更新时间:2023-10-31 08:04:32 25 4
gpt4 key购买 nike

我在我的 swift 应用程序中从头开始编写不断增长的 UITextView。我在 view 上放置了一个 textView,如下所示:

enter image description here

它就在键盘的正上方。

textView 具有附加到 view 的约束:leadingbottomtop code> 和 trailing,都等于 4

View 有以下限制:

trailingleadingbottomtopheight

Height 是我代码中的一个导出。我正在检查 textView 中有多少行,并据此修改 height:

func textViewDidChange(textView: UITextView) { //Handle the text changes here
switch(textView.numberOfLines()) {
case 1:
heightConstraint.constant = 38
break
case 2:
heightConstraint.constant = 50
break
case 3:
heightConstraint.constant = 70
break
case 4:
heightConstraint.constant = 90
break
default:
heightConstraint.constant = 90
break
}
}

上面的行数是通过这个扩展计算出来的:

extension UITextView{

func numberOfLines() -> Int{
if let fontUnwrapped = self.font{
return Int(self.contentSize.height / fontUnwrapped.lineHeight)
}
return 0
}
}

textView 的初始高度是 38textView 中的初始字体大小为 15

现在,它工作得很好,当用户开始输入新行时,但是 textView 没有设置在 View 的完整范围内。我的意思是,它看起来像这样:

enter image description here

它应该是这样的:

enter image description here

为什么要添加这个额外的空白区域,我该如何去除它?

目前当新行出现时有这个空白,但是当用户滚动 textView 使文本居中并摆脱空白时 - 它永远消失了,用户无法滚动它再次向上,所以白线就在那里。所以对我来说,刷新内容似乎有些问题,但也许你知道得更多 - 你能给我一些提示吗?

最佳答案

这是我在我正在开发的一个应用程序的评论部分中使用的一种有点不同的方法。这与 Facebook Messenger iOS 应用程序的输入字段非常相似。更改了导出名称以匹配您问题中的名称。

//Height constraint outlet of view which contains textView.
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var textView: UITextView!

//Maximum number of lines to grow textView before enabling scrolling.
let maxTextViewLines = 5
//Minimum height for textViewContainer (when there is no text etc.)
let minTextViewContainerHeight = 40

func textViewDidChange(textView: UITextView) {
let textViewVerticalInset = textView.textContainerInset.bottom + textView.textContainerInset.top
let maxHeight = ((textView.font?.lineHeight)! * maxTextViewLines) + textViewVerticalInset
let sizeThatFits = textView.sizeThatFits(CGSizeMake(textView.frame.size.width, CGFloat.max))

if sizeThatFits.height < minTextViewContainerHeight {
heightConstraint.constant = minTextViewContainerHeight
textView.scrollEnabled = false
} else if sizeThatFits.height < maxHeight {
heightConstraint.constant = sizeThatFits.height
textView.scrollEnabled = false
} else {
heightConstraint.constant = maxHeight
textView.scrollEnabled = true
}
}

func textViewDidEndEditing(textView: UITextView) {
textView.text = ""
heightConstraint.constant = minTextViewContainerHeight
textView.scrollEnabled = false
}

关于ios - 光标在 UITextView 中的奇怪定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39840820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com