更改 UILabel 行数后调整 UIStackView [英] Resizing UIStackView after changing UILabel number of lines

查看:25
本文介绍了更改 UILabel 行数后调整 UIStackView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 iOS 应用有一个带有以下布局的 UITableViewCell 的 tableview(1 个包含 2 个标签和 1 个按钮的 stackview)

My iOS app has a tableview with one UITableViewCell with the following layout (1 stackview containing 2 labels and 1 button)

当用户点击按钮时,中央标签的行数从 0 到 2,如下所示:

When the user taps the button the number of lines of the central label goes from 0 to 2 and will look like this:

现在这里有两个问题:

1) 调整 UIStackView 的大小

1) Resizing the UIStackView

2) 调整单元格大小

我为问题 1 找到了一个非最佳解决方案,它包括在堆栈中添加一个空视图.(invalidateIntrinsicContentSize 不起作用).

I have found a not-optimal solution for problem 1, which consists of adding an empty view in the stack. (invalidateIntrinsicContentSize was not working).

let emptyView = UIView()
emptyView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
stackView.addArrangedSubview(emptyView)

正如您在第二个屏幕截图中看到的,单元格没有调整大小,我不确定这是由于堆栈视图还是单元格本身造成的.

As you can see in the second screenshot the cell doesn't resize and I'm not sure if this is due to the stackview or the cell itself.

我想指出一个事实,即我在 UITableViewCell 子类中编写代码,因为按钮事件是在其中处理的.

I would like to point the fact that I'm writing code inside the UITableViewCell subclass as the button event is handled inside it.

对于记录,Tableview 正在使用动态调整大小:

For the records The Tableview is using dynamic sizing:

// dynamic cell sizing 
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return CGFloat(cellEstimatedHeight)
}

推荐答案

UIStackView 可能是也可能不是你最好的选择……它的设计更多是为了在自己的框架内排列视图,而不是调整它自己的视图框架.

UIStackView may or may not be your best bet... it's designed more for arranging views inside its own frame, rather than adjusting its own frame to the views.

对于像您在那里一样简单的布局,只布置具有正常约束的元素可能会好得多.

For a layout as simple as you have there, it would probably be much better to just lay out the elements with normal constraints.

看看这个例子:https://github.com/DonMag/DynamicCellHeight

表 B 是完成布局的一种方式(表 A 是我玩过的另一种布局).

Table B is one way of accomplishing your layout (Table A was for another layout I played around with).

当单元格调整大小时,我不得不做一些小技巧才能使主标签保持原位......可能会找到更好的方法.(重新编辑 - 是的,找到了更好的方法)

I had to do a little trickery to get the main label to stay in place while the cell resized... could probably find a better way. (Re-Edit - yep, found a better way)

让我知道它是否有意义 - 毫无疑问,您会想要做一些调整.

Let me know if it makes sense - no doubt you'll want to do some tweaking.

这篇关于更改 UILabel 行数后调整 UIStackView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆