ios 如何计算字符串的高度?

3wabscal  于 2023-03-24  发布在  iOS
关注(0)|答案(8)|浏览(189)

我试图调整单元格高度大小以适应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是字符串数组。
这是我的项目文件,如果有人看一下的话:http://www.filedropper.com/test_37

cbwuti44

cbwuti441#

为什么不在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

希望这能帮上忙

v09wglhw

v09wglhw2#

你可以这样做,但我已经实现了不同的方式。这里是代码的样本,你可以做到这一点。

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)")
afdcj2ne

afdcj2ne3#

创建String扩展名

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

nkkqxpd94#

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

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

uqjltbpv5#

试试这个...

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;
mlnl4t2r

mlnl4t2r6#

我看了你的代码,我能解决它。
首先,在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设置为width,而将width设置为height。它应该是:

CGSizeMake(UIScreen.mainScreen().bounds.size.width, CGFloat.max)

我认为最好使用单元格直接包含的视图的宽度(collectionView),但这只是我个人的观点。
第二,你需要启用AutoLayout。转到你的Main.storyboard文件,并确保选择了Use Auto Layout

现在您需要添加constraints。(您可以阅读更多关于自动布局和约束here的内容)
添加约束的方法有很多种,最简单的方法是控制单击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

And these for your CollectionView

CollectionView.top = view.top
CollectionView.leading = view.leading
CollectionView.trailing = view.trailing
CollectionView.bottom = view.bottom

我已经附加了项目,修改与AutoLayout在这里下面。
Modified project

编辑:

方法2 -不使用AutoLayout。
这也可以在不使用AutoLayout的情况下通过手动更新collectionView:willDisplayCell:中单元格的标签高度来实现。我相信有更好的替代方案,在此之前我个人会尝试AutoResizingMasks
Project without AutoLayout

ct3nt3jp

ct3nt3jp7#

extension String{
  
  func height(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)
    }}
vbopmzt1

vbopmzt18#

在Swift 5中,您可以使用以下代码

let text = arrRatingData[indexPath.row].comment
let font = UIFont.systemFont(ofSize: 13.5)
let size = CGSize(width: self.collectionView.frame.width - 80, height: CGFloat.greatestFiniteMagnitude)
let options = NSStringDrawingOptions.usesLineFragmentOrigin
let attributes = [NSAttributedString.Key.font: font]
let height = NSString(string: text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height

相关问题