Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MyLayout 能不能結合autolayout,動態算出custom view 的高度? #79

Closed
Elvis5566 opened this issue Aug 23, 2018 · 5 comments
Closed

Comments

@Elvis5566
Copy link

Elvis5566 commented Aug 23, 2018

歐陽大哥你好,

我原本有個cell, 長這樣
https://i.imgur.com/15MZNS8.png
title, subtitle 可能會有多行,透過autoLayout, 可以動態得到適合的高度

新的layout需要在subtitle 底下加一個vertical FlowLayout
像這樣 https://i.imgur.com/15MZNS8.png
黃色部分是FlowLayout

請問有沒有辨法讓這個FlowLayou.wrapContentHeight = YES
並且像原先一樣用autoLayout, 讓整個cell高度為
title.height + subtitle.height + FlowLayout.height + subviewSpaces

感謝你!

@youngsoft
Copy link
Owner

你好。

解决方法一:

这是一个Autolayout 和MyLayout结合的比较典型的例子。因为MyLayout和AutoLayout的布局机制不相同。所以一般来说MyLayout中的wrapContentHeight是不能影响到通过autolayout来实现动态高度的。但是不是没有办法,经过我这边的实践,你可以建立一个MyFlowLayout的派生类,然后重载这个类的intrinsicContentSize 如下:


//这个函数是返回布局视图的固有尺寸值,这里可以巧妙的用sizeThatFit来评估出动态高度。
//其实UILabel也是内部重载了这个方法,就能实现在不设置高度约束的情况下的自动换行以及高度计算的能力。
-(CGSize)intrinsicContentSize
{
    CGSize sz = [self sizeThatFits:CGSizeMake(注意这个宽度一定要是flow layout的真实宽度, 0)];
    return sz;
}

主要如果你通过XIB或者SB来加入flowlayout的话,记得要设置flowlayout的wrapContentHeight = YES哦。当你实现了intrinsicContentSize函数后,你就可以不再设置flowlayout的高度autolyout约束,只需要设置宽度autolayout约束即可。 然后就按普通的那种可以撑大cell高度的方式来设置约束即可实现动态高度了。

你提的这个需求非常的好,目前的版本只能暂时通过重载intrinsicContentSize方法来解决问题,然后我会尽快的升级一个版本,在内部实现这个方法从而解决AutoLayout和MyLayout结合并且动态高度的问题。再次非常感谢你的这个需求的提出

解决方案二:

就是将这个cell的所有布局和约束都改为MyLayout的方法,MyLayout也是支持XIB和SB结合的。然后动态cell高度的方法可以在AllTest1TableViewCell中找到答案。

@youngsoft
Copy link
Owner

附上我这边的约束设置:

附上我这边实验的约束设置

image

@Elvis5566
Copy link
Author

Elvis5566 commented Aug 24, 2018

謝謝你的解答!
對於第一個做法,我有個疑問
在storyboard 設了constraints後,這個layout的寬度就自動決定了
但在這行code
[self sizeThatFits:CGSizeMake(注意这个宽度一定要是flow layout的真实宽度, 0)];
我需要去設定最終MyLayout 的寬度, 所以代表我要手動去算出AutoLayout完的寬度?
這樣似乎就失去用autoLayout的目的
有點好奇如果你在內部實作這個功能,要怎麼處理這個問題
我的意思是,如果我不需要明確指定myLayout的寬度
代表autoLayout完後才能進行myLayout
但是要autoLayout 又需要用到myLayout的size(height)
這樣似乎是deadlock

@youngsoft
Copy link
Owner

这是一个好问题,我也需要思考一下,当时我在回复你时也一直在想这个问题。然后我想从autolayout中的其他属性中是否能够找到解决问题的方法。

@youngsoft
Copy link
Owner

您好,这是一个迟来的更新,目前在最新发布的1.7.0版本中布局视图内部通过重载intrinsicContentSize的方法已经实现了布局视图尺寸自适应和autolayout结合的问题了,处理的例子请参考最新的项目中的DEMO文件:AllTest12ViewController.m。以及MyLayout高度自适应在UITableViewCell中的最新使用形式, 请参考具体的实现代码。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants