如何计算String的高度?

时间:2015-12-14 08:53:22

标签: ios swift

我正在尝试调整单元格高度调整大小以适应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

7 个答案:

答案 0 :(得分:4)

为什么不在ObjC中尝试这个

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
  <input data-maxsale="9" data-maxsaleid="27595" name="cart[3839][qty]" value="10" title="Qty" class="input-text qty" maxlength="12">
  <div class="maxsalenotifcation maxsaleid-27595">
    <p>
      placeholder
    </p>
  </div>
</div>
<div>
  <input data-maxsale="3" data-maxsaleid="27757" name="cart[3841][qty]" value="4" title="Qty" class="input-text qty" maxlength="12">
  <div class="maxsalenotifcation maxsaleid-27757">
    <p>
      placeholder
    </p>
  </div>
</div>

这将给予CGRect。从中获取高度。在属性参数中设置字体大小等。

<强>更新

代替这个

 [text boundingRectWithSize:CGSizeMake(maxWidth, maxHeight)
                                  options:NSStringDrawingUsesLineFragmentOrigin
                               attributes:nil context:nil]

使用此

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

希望这有帮助

答案 1 :(得分:2)

你可以这样做,但我已经以不同的方式实现了它。以下是您可以执行的代码示例。

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

答案 2 :(得分:1)

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

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
}

答案 3 :(得分:0)

试试这个......

   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;

答案 4 :(得分:0)

我看了你的代码,我能够解决它。

首先,在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),但这仅仅是我个人的观点。

其次,您需要启用AutoLayout。转到Main.storyboard文件,确保选中Use Auto Layout

Enable AutoLayout

现在您需要添加constraints。 (您可以阅读有关AutoLayout和约束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

这些适合您的CollectionView

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

我已经附加了项目,使用下面的AutoLayout进行了修改。

Modified project

修改

方法2 - 没有AutoLayout。

这也可以通过手动更新collectionView:willDisplayCell:中单元格的标签高度而不使用AutoLayout来实现。我确定有更好的选择,我会在此方法之前亲自尝试AutoResizingMasks

Project without AutoLayout

答案 5 :(得分:0)

extension String {

func height(withConstrainedWidth width:CGFloat,font:UIFont) - &gt; 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)
}}

答案 6 :(得分:0)

Crate an String extension

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