Ios 如何计算一根绳子的高度?

Ios 如何计算一根绳子的高度?,ios,swift,Ios,Swift,我正在尝试调整单元格高度大小以适应UILabel文本,但它不起作用 var mySize = CGFloat() func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithRe

我正在尝试调整单元格高度大小以适应UILabel文本,但它不起作用

var mySize = CGFloat()
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! cellView

        cell.myLabel.text = self.items[indexPath.item]
        cell.myLabel.bounds.size.height = self.mySize

        cell.backgroundColor = UIColor.yellowColor()

        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat
        {
            let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
            label.numberOfLines = 0
            label.lineBreakMode = NSLineBreakMode.ByWordWrapping
            label.font = font
            label.text = items[indexPath.row]

            label.sizeToFit()
            return label.frame.height
        }

        let font = UIFont(name: "Helvetica Neue", size: 30)
        let detailHeight = heightForLabel(items[indexPath.row], font: font!, width: UIScreen.mainScreen().bounds.size.width)

        self.mySize = detailHeight

        return CGSizeMake(UIScreen.mainScreen().bounds.size.width, 358 + detailHeight)
    }
有什么建议吗?我应该换一种方式吗?求你了,我需要帮助。。问题在于UILabel文本是在
cellForItemAtIndexPath
中设置的,而
items
是字符串数组

这是我的项目文件,如果有人观看它:

您可以这样做,但我以不同的方式实现了它。下面是您可以执行此操作的代码示例

 let desiredWidth: CGFloat = tableView.bounds.size.width
 let label: UILabel = UILabel()

 let desiredString = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."

 label.text = desiredString
 label.numberOfLines = 0;
 label.lineBreakMode = NSLineBreakMode.ByWordWrapping
 let size: CGSize = label.sizeThatFits(CGSizeMake(desiredWidth, CGFloat.max))

 print("Label height you can set to your cell: \(size.height)")

为什么不在ObjC中尝试这个呢

 [text boundingRectWithSize:CGSizeMake(maxWidth, maxHeight)
                                  options:NSStringDrawingUsesLineFragmentOrigin
                               attributes:nil context:nil]
这将给出CGRect。从中获取高度。在属性参数中设置字体大小等

更新

代替这个

let detailHeight = heightForLabel(items[indexPath.row], font: font!, width: UIScreen.mainScreen().bounds.size.width)
用这个

let height = items[indexPath.row].boundingRectWithSize(CGSizeMake(CGFloat.max,UIScreen.mainScreen().bounds.size.width), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font!], context: nil).size.height
希望这有帮助

试试这个

   NSString *yourText = @"Your string";
    CGSize lableWidth = CGSizeMake(300, CGFLOAT_MAX);
    CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"CALIBRI" size:17] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping];
    int calculatedHeight = requiredSize.height;
    return (float)calculatedHeight;

我看了一下你的代码,我能解决它

首先,在
ViewController
类的第71行:

let height = items[indexPath.row].boundingRectWithSize(CGSizeMake(CGFloat.max, UIScreen.mainScreen().bounds.size.width), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font!], context: nil).size.height
您意外地将CGFloat.max设置为宽度,将宽度设置为高度。应该是:

CGSizeMake(UIScreen.mainScreen().bounds.size.width, CGFloat.max)
我认为最好使用单元格直接包含的视图的宽度(在
collectionView
中),但这只是我个人的观点

其次,您需要启用自动布局。转到
Main.storyboard
文件,确保选中了
Use Auto Layout

现在需要添加
约束
。(您可以阅读有关自动布局和约束的更多信息)

有不同的方法可以添加约束。最简单的方法是控制并单击UI元素,然后将鼠标拖动到要设置约束的元素

您需要为单元格添加以下约束:

ImageView.top = cell.top
ImageView.leading = cell.leading
ImageView.trailing = cell.trailing
ImageView.bottom = MyLabel.top + 8 (your padding)
MyLabel.leading = cell.leading
MyLabel.trailing = cell.trailing
MyLabel.bottom = cell.bottom
这些是你的收藏视图

CollectionView.top = view.top
CollectionView.leading = view.leading
CollectionView.trailing = view.trailing
CollectionView.bottom = view.bottom
我已经附加了这个项目,在下面用AutoLayout进行了修改

编辑:

方法2-无自动布局

这也可以通过在
collectionView:willDisplayCell:
中手动更新单元格的标签高度来实现,而无需使用自动布局。我相信还有更好的选择,在采用这种方法之前,我个人会尝试
AutoResizingMasks


我创建了这个方法来获取标签的高度。您需要提供标签的静态宽度和字体

func dynamicHeight(font: UIFont, width: CGFloat) -> CGFloat{
    let calString = NSString(string: self)
    let textSize = calString.boundingRectWithSize(CGSizeMake(width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin|NSStringDrawingOptions.UsesFontLeading, attributes: [NSFontAttributeName: font], context: nil)
    return textSize.height
}
扩展字符串{

func高度(withConstrainedWidth-width:CGFloat,font:UIFont)->CGFloat{

    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)

    let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
    return ceil(boundingBox.height)
}}

包装一个字符串扩展名

extension String {
    func heightOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSFontAttributeName: font]
        let size = self.size(attributes: fontAttributes)
        return size.height
    }
}
获取字符串的高度,如下所示

let str = "Hello world"
let strHgt = str.heightOfString(usingFont: UIFont.systemFont(ofSize: 12))

您是否已将自己设置为collectionView的代理?此外,它应该是
heightForLabel
中的
return label.frame.size.height
function@mbo42-是的,仍然不工作..函数被调用了吗?得到了什么结果?顺便说一句,在
cellForItemAtIndexPath
中,您不需要修改单元格的框架@mbo42更新了带有项目链接的问题。也许你想看看!我如何以及在哪里使用它?这也不起作用。如果你想查看,请在我的项目中添加一个链接:当前不在笔记本电脑上,因此进行简单猜测以排除可能。UILabel的Lines属性不应设置为0故事板中标签的高度/xib您没有使用自动布局。当前您必须自己设置UIImageView和UILabel的框架。这就是缺少的内容。无论您在Interface Builder中创建了多大的框架,它们都将在运行时保留该框架。使用字符串高度的计算在单元格中设置框架,或者使用autolayou我在输出中得到了:-但是如何设置标签高度?在重新加载tableview时必须计算标签高度,以便在
HeightForRowatineXpath
中使用它。请参见重新加载tableview时,tableview委托方法被称为
HeightForRowatineXpath
是其委托方法之一要将
CGFloat
值返回到此值,以便您可以返回高于此值的值,做得很好!A问题;您是否能够在不使用自动布局的情况下执行此操作?因为我有一个没有自动布局的应用程序。我想您可以在进行计算后手动设置ImageView和MyLabel的帧。请注意,您不需要实现自动布局仅因为选中了该框,就可以为所有视图进行布局。您可以选择仅为该ViewController进行布局。您还可以为此解决方案提供一个没有自动布局的示例项目吗?这将非常有用,因为我以前从未使用过自动布局:)好的,。我通过在
willDisp中移动标签的高度设置来实现layCell
。出于性能原因,我还添加了计算高度的缓存。不过,我仍然建议使用自动布局而不是这种方法。非常感谢!您强烈建议我使用自动布局吗?使用自动布局会使其更稳定吗?或者,在这种情况下,如果我使用自动布局,我如何仅对该视图控制器使用自动布局ve具有选项卡栏控制器和导航控制器的多视图控制器,但要仅为该视图控制器设置自动布局吗?