gpt4 book ai didi

ios - 在键入时调整包含 UITextView 的 UITableViewCell 的大小

转载 作者:IT王子 更新时间:2023-10-29 08:09:59 25 4
gpt4 key购买 nike

我有一个包含自定义单元格的 UITableViewController。每个单元格都是使用 nib 创建的,并包含一个不可滚动的 UITextView。我在每个单元格内添加了约束,以便单元格调整其高度以适应 UITextView 的内容。所以最初我的 Controller 看起来像这样:

initial state

现在我希望当用户在单元格中键入内容时,其内容会自动适应。这个问题问过很多次了,具体见thisthe second answer here .因此,我在我的代码中编写了以下委托(delegate):

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text {
[self.tableView beginUpdates];
[self.tableView endUpdates];
return YES;
}

然而,它会导致以下奇怪的行为:所有约束都被忽略,所有单元格高度都折叠到最小值。见下图:

wrong behavior

如果我上下滚动 tableView 以强制调用新的 cellForRowAtIndexPath,我会恢复单元格的正确高度:

correct behavior

请注意,我没有实现 heightForRowAtIndexPath,因为我希望 autoLayout 会处理这个问题。

有人可以告诉我我做错了什么或帮助我吗?非常感谢!

最佳答案

这是一个适合我的快速解决方案。如果您使用自动布局,则需要为 estimatedRowHeight 赋值,然后返回 UITableViewAutomaticDimension 作为行高。最后在 TextView 委托(delegate)中执行类似于下面的操作。

override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 44.0
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}

// MARK: UITextViewDelegate
func textViewDidChange(textView: UITextView) {

// Calculate if the text view will change height, then only force
// the table to update if it does. Also disable animations to
// prevent "jankiness".

let startHeight = textView.frame.size.height
let calcHeight = textView.sizeThatFits(textView.frame.size).height //iOS 8+ only

if startHeight != calcHeight {

UIView.setAnimationsEnabled(false) // Disable animations
self.tableView.beginUpdates()
self.tableView.endUpdates()

// Might need to insert additional stuff here if scrolls
// table in an unexpected way. This scrolls to the bottom
// of the table. (Though you might need something more
// complicated if editing in the middle.)

let scrollTo = self.tableView.contentSize.height - self.tableView.frame.size.height
self.tableView.setContentOffset(CGPoint(x: 0, y: scrollTo), animated: false)

UIView.setAnimationsEnabled(true) // Re-enable animations.
}

关于ios - 在键入时调整包含 UITextView 的 UITableViewCell 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31595524/

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