ios - 如何根据自动布局约束使容器 View 的高度动态化?

标签 ios objective-c interface-builder autolayout

我在 Xcode 界面生成器中制作了一个自定义 TableViewCell,其中 UILabel 和 UITextView 垂直堆叠,并设置了它们与容器单元 View 之间的垂直间距的约束。

enter image description here

UITextView 可能需要容纳大量文本,我不希望出现垂直滚动条,因此我使用 [NSString sizeWithFont:constraintTosize:] 计算 UITextView 的高度,并用这个新高度设置其框架。

但是这不起作用。

然后我注意到 .xib 中的自定义单元格具有固定的行高。我想知道这个固定高度和垂直约束是否决定了 UITextView 的高度,并且我无法更改它?

如果我想要相反怎么办:当我设置 UITextView 的高度时,包含单元格的高度是根据约束计算的?这可能吗?

最佳答案

下面的代码应该会有帮助。我能够按照您的描述进行操作,并在名为 CustomCell 的自定义 UITableViewCell 中处理 UILabel 上的可变文本量。 CustomCell 使用未修改的样板 UITableViewCell 代码。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    // Using some sample text in here for testing purposes.
    NSString *sampleText = @"The UITextView may need to hold a lot of text, I don't want vertical scrollbar to appear. The UITextView may need to hold a lot of text, I don't want vertical scrollbar to appear.";

    cell.textLabel.text = sampleText;
    [cell.textLabel layoutIfNeeded];

    return cell.textLabel.frame.size.height;
}

最后但同样重要的是,使用 AutoLayout 在 CustomCell 中设置您的 UILabel。点击此链接查看操作步骤:https://stackoverflow.com/a/16009707/885189

关于ios - 如何根据自动布局约束使容器 View 的高度动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19853376/

相关文章:

ios - 在 iPhone 的 iOS 7 中打开相机时横向模式下的方向问题

ios - 根据宽度调整 UIImage 的大小

objective-c - 在我的 xib 文件中委托(delegate)给文件所有者是什么意思?

objective-c - NSWindow,按下 ENTER 键 : how to limit the key listening to the focused NSControl?

ios - UIButton 的子类使用 Interface Builder 连接到父 View Controller 的 IBAction?

ios - 检测 UILabel 换行符。动态地将项目放入 UITableViewCell

ios - 编辑 CoreData 对象然后保存上下文

ios - 如何异步下载和缓存视频以供在我的应用中使用?

php - 使用 NSURLSession 将带符号 (&) 的字符串从 iOS 传递到 PHP/MySQL

iphone - 使用父/子上下文时批量大小不起作用