Подтвердить что ты не робот

Как рассчитать высоту строки?

Я пытаюсь настроить размер высоты ячейки, чтобы соответствовать тексту 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

4b9b3361

Ответ 1

Почему бы не попробовать это в ObjC

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

Это даст CGRect. Получите высоту от нее. установить размер шрифта и т.д. в параметрах атрибутов.

UPDATE

Вместо этого

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

Надеюсь, что это поможет

Ответ 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 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)")

Ответ 3

Я создаю этот метод для получения высоты метки. Вам необходимо указать метку static Width и label font

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
}

Ответ 4

Попробуйте это...

   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;

Ответ 5

Я взглянул на ваш код, и я смог его решить.

Во-первых, в строке 71 в вашем классе ViewController:

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.

Включить автозапуск

Теперь вам нужно добавить constraints. (Вы можете больше узнать об AutoLayout и ограничениях здесь)

Существуют разные способы добавления ограничений. Самый простой способ - это щелкнуть элемент пользовательского интерфейса и перетащить мышь на элемент, которому вы хотите установить ограничение.

Вам нужно добавить следующие ограничения для вашей ячейки:

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 ниже.

Измененный проект

Edit:

Подход 2 - без автозапуска.

Это также может быть достигнуто без использования AutoLayout, вручную обновив высоту метки ячейки в collectionView:willDisplayCell:. Я уверен, что есть лучшие альтернативы, я лично попробовал бы AutoResizingMasks до этого подхода.

Проект без автозапуска

Ответ 6

extension Строка {

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

Ответ 7

Соединить расширение строки

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