Resizing UIStackView after changing UILabel number of lines

拟墨画扇 提交于 2019-12-10 10:13:42

问题


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

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

Now there are two problems here:

1) Resizing the UIStackView

2) Resizing the cell

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.

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

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)
}

回答1:


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.

Take a look at this example: https://github.com/DonMag/DynamicCellHeight

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.



来源:https://stackoverflow.com/questions/42984856/resizing-uistackview-after-changing-uilabel-number-of-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!