Regolare l'altezza UILabel a seconda del testo

voti
289

Considerate Ho il seguente testo in un UILabel(una lunga serie di testo dinamico):

Dal momento che l'esercito alieno oltrepassa di gran lunga la squadra, i giocatori devono utilizzare il mondo post-apocalittico a loro vantaggio, come ad esempio in cerca di riparo dietro cassonetti, pilastri, automobili, calcinacci e altri oggetti.

Voglio ridimensionare l' UILabel'saltezza in modo che il testo può andare bene. Io sto usando seguenti proprietà UILabelper rendere il testo all'interno di avvolgere.

myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;

Per favore fatemi sapere se non sto andando nella direzione giusta. Grazie.

È pubblicato 15/01/2009 alle 12:19
fonte dall'utente
In altre lingue...                            


34 risposte

voti
394

sizeWithFont constrainedToSize:lineBreakMode:è il metodo da utilizzare. Un esempio di come usarlo è qui sotto:

//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];   

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
Risposto il 15/01/2009 a 16:01
fonte dall'utente

voti
231

Stavi nella giusta direzione. Tutto quello che dovete fare è:

myUILabel.numberOfLines = 0;
myUILabel.text = @"Enter large amount of text here";
[myUILabel sizeToFit];
Risposto il 20/08/2009 a 05:45
fonte dall'utente

voti
41

In iOS 6 Apple ha aggiunto una proprietà da UILabel che semplifica notevolmente il ridimensionamento verticale dinamica delle etichette: preferredMaxLayoutWidth .

Utilizzando questa struttura in combinazione con lineBreakMode = NSLineBreakByWordWrapping e sizeToFit metodo permette facilmente ridimensionare un'istanza UILabel all'altezza che ospita l'intero testo.

Una citazione dalla documentazione iOS:

preferredMaxLayoutWidth PREFERITE larghezza massima (in punti) per un'etichetta multilinea.

Discussione Questa proprietà riguarda la dimensione dell'etichetta quando i vincoli di layout sono applicati ad esso. Durante il layout, se il testo si estende oltre la larghezza specificata da questa proprietà, il testo aggiuntivo viene fatta fluire ad una o più nuove linee, aumentando così l'altezza dell'etichetta.

Un campione:

...
UILabel *status = [[UILabel alloc] init];
status.lineBreakMode = NSLineBreakByWordWrapping;
status.numberOfLines = 5; // limits to 5 lines; use 0 for unlimited.

[self addSubview:status]; // self here is the parent view

status.preferredMaxLayoutWidth = self.frame.size.width; // assumes the parent view has its frame already set.

status.text = @"Some quite lengthy message may go here…";
[status sizeToFit];
[status setNeedsDisplay];
...
Risposto il 04/11/2013 a 22:14
fonte dall'utente

voti
34

Invece di fare questo a livello di codice, è possibile fare questo in Storyboard / XIB durante la progettazione.

  • Set di UILabel numero di linee di proprietà da 0 a attributi ispettore.
  • Quindi impostare larghezza vincolo / (o) iniziali e finali vincolo secondo il requisito.
  • Poi set vincolo altezza con valore minimo . Infine selezionare il vincolo di altezza e si è aggiunto nella finestra di ispezione dimensioni quello accanto ispezione degli attributi, modificare il vincolo di altezza relazione da pari a - superiore .
Risposto il 18/06/2015 a 19:08
fonte dall'utente

voti
28

Controllare questo lavoro perfettamente senza l'aggiunta di singola linea di codice. (Usando Autolayout)

Ho fatto una demo per voi secondo la vostra esigenza. Scaricalo dal basso di collegamento,

AutoResize UIView e UILabel

Guida passo passo: -

Fase 1: - Set limitare al UIView

1) Leading 2) Top 3) Trailing (da MAINVIEW)

entrare descrizione dell'immagine qui

Fase 2: - Impostare Vincola per etichetta 1

1) Leading 2) Top 3) Trailing (Dalla sua superview)

entrare descrizione dell'immagine qui

Fase 3: - Impostare Vincola per etichetta 2

1) Leading 2) Trailing (Dalla sua superview)

entrare descrizione dell'immagine qui

Fase 4: - La maggior parte difficile dare botton UILabel da UIView.

entrare descrizione dell'immagine qui

Fase 5: - (opzionale) Set vincolare a UIButton

1) Leading 2) inferiore 3) Trailing 4) Altezza fissa (da MAINVIEW)

entrare descrizione dell'immagine qui

Produzione :-

entrare descrizione dell'immagine qui

Nota: - Assicurarsi di aver impostato Numero di righe = 0 nella proprietà Label.

entrare descrizione dell'immagine qui

Spero che questa informazione sufficiente per capire Ridimensiona automaticamente UIView in base all'altezza del UILabel e Ridimensiona automaticamente UILabel Secondo il testo.

Risposto il 26/04/2016 a 10:52
fonte dall'utente

voti
15

Grazie ragazzi per l'aiuto, ecco il codice ho provato, che sta lavorando per me

   UILabel *instructions = [[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
   NSString *text = @"First take clear picture and then try to zoom in to fit the ";
   instructions.text = text;
   instructions.textAlignment = UITextAlignmentCenter;
   instructions.lineBreakMode = NSLineBreakByWordWrapping;
   [instructions setTextColor:[UIColor grayColor]];

   CGSize expectedLabelSize = [text sizeWithFont:instructions.font 
                                constrainedToSize:instructions.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];

    CGRect newFrame = instructions.frame;
    newFrame.size.height = expectedLabelSize.height;
    instructions.frame = newFrame;
    instructions.numberOfLines = 0;
    [instructions sizeToFit];
    [self addSubview:instructions];
Risposto il 23/11/2010 a 18:20
fonte dall'utente

voti
12

Soluzione iOS7 nota e sopra iOS7

//
//  UILabel+DynamicHeight.m
//  For StackOverFlow
//
//  Created by Vijay on 24/02/14.
//  Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//

#import <UIKit/UIKit.h>

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

#define iOS7_0 @"7.0"

@interface UILabel (DynamicHeight)

/*====================================================================*/

/* Calculate the size,bounds,frame of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */

-(CGSize)sizeOfMultiLineLabel;

@end


//
//  UILabel+DynamicHeight.m
//  For StackOverFlow
//
//  Created by Vijay on 24/02/14.
//  Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//

#import "UILabel+DynamicHeight.h"

@implementation UILabel (DynamicHeight)
/*====================================================================*/

/* Calculate the size,bounds,frame of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */
-(CGSize)sizeOfMultiLineLabel{

    NSAssert(self, @"UILabel was nil");

    //Label text
    NSString *aLabelTextString = [self text];

    //Label font
    UIFont *aLabelFont = [self font];

    //Width of the Label
    CGFloat aLabelSizeWidth = self.frame.size.width;


    if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
        //version < 7.0

        return [aLabelTextString sizeWithFont:aLabelFont
                            constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                lineBreakMode:NSLineBreakByWordWrapping];
    }
    else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
        //version >= 7.0

        //Return the calculated size of the Label
        return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                        NSFontAttributeName : aLabelFont
                                                        }
                                              context:nil].size;

    }

    return [self bounds].size;

}

@end
Risposto il 24/02/2014 a 11:16
fonte dall'utente

voti
10

Dal momento che sizeWithFont è deprecato io uso questo uno invece.

questo uno ottenere attributi specifici di etichetta.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text{

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];

    return ceil(rect.size.height);
}
Risposto il 13/11/2014 a 23:40
fonte dall'utente

voti
6

Ecco una versione categoria:

UILabel + AutoSize.h #import

@interface UILabel (AutoSize)

- (void) autosizeForWidth: (int) width;

@end

UILabel + AutoSize.m

#import "UILabel+AutoSize.h"

@implementation UILabel (AutoSize)

- (void) autosizeForWidth: (int) width {
    self.lineBreakMode = UILineBreakModeWordWrap;
    self.numberOfLines = 0;
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    CGSize expectedLabelSize = [self.text sizeWithFont:self.font constrainedToSize:maximumLabelSize lineBreakMode:self.lineBreakMode];
    CGRect newFrame = self.frame;
    newFrame.size.height = expectedLabelSize.height;
    self.frame = newFrame;
}

@end
Risposto il 10/04/2013 a 18:58
fonte dall'utente

voti
6

È possibile implementare TableViewController's (UITableViewCell *)tableView:cellForRowAtIndexPath il metodo nel modo seguente (per esempio):

#define CELL_LABEL_TAG 1

- (UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = @"my long text";

    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero  reuseIdentifier:identifier] autorelease];
    }

    CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
    CGFloat height = [self textHeight:text] + 10;
    CGRect frame = CGRectMake(10.0f, 10.0f, width, height);

    UILabel *cellLabel = [[UILabel alloc] initWithFrame:frame];
    cellLabel.tag = CELL_LABEL_TAG;
    cellLabel.textColor = [UIColor blackColor];
    cellLabel.backgroundColor = [UIColor clearColor];
    cellLabel.textAlignment = UITextAlignmentLeft;
    cellLabel.font = [UIFont systemFontOfSize:12.0f];
    [cell.contentView addSubview:cellLabel];
    [cellLabel release];

    return cell;
}

UILabel *label = (UILabel *)[cell viewWithTag:CELL_LABEL_TAG];
label.text = text;
label.numberOfLines = 0;
[label sizeToFit];
return cell;

Anche utilizzare NSString's sizeWithFont:constrainedToSize:lineBreakMode:metodo per calcolare l'altezza del testo.

Risposto il 15/01/2009 a 15:10
fonte dall'utente

voti
4

Il modo più semplice e migliore che ha lavorato per me era di applicare vincolo di altezza per etichettare e impostare la priorità al basso , vale a dire, (250) in storyboard.

Quindi non è necessario preoccuparsi di calcolare l'altezza e la larghezza di programmazione, grazie a storyboard.

Risposto il 16/05/2016 a 16:43
fonte dall'utente

voti
4

E per coloro che stanno migrando verso iOS 8, ecco un'estensione classe per Swift:

extension UILabel {

    func autoresize() {
        if let textNSString: NSString = self.text {
            let rect = textNSString.boundingRectWithSize(CGSizeMake(self.frame.size.width, CGFloat.max),
                options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                attributes: [NSFontAttributeName: self.font],
                context: nil)
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, rect.height)
        }
    }

}
Risposto il 27/08/2014 a 10:18
fonte dall'utente

voti
3

Metodo aggiornato

+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {

    CGSize constraint = CGSizeMake(width, 20000.0f);
    CGSize size;

    CGSize boundingBox = [text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:font}
                                                  context:nil].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}
Risposto il 06/07/2015 a 12:21
fonte dall'utente

voti
2

Questa è una riga di codice per ottenere l'altezza UILabel usando Objective-C:

labelObj.numberOfLines = 0;
CGSize neededSize = [labelObj sizeThatFits:CGSizeMake(screenWidth, CGFLOAT_MAX)];

e l'utilizzo di .height si otterrà l'altezza delle etichette come segue:

neededSize.height
Risposto il 07/03/2017 a 13:22
fonte dall'utente

voti
2

Per fare questo in Swift3 seguito è il codice:

 let labelSizeWithFixedWith = CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)
            let exactLabelsize = self.label.sizeThatFits(labelSizeWithFixedWith)
            self.label.frame = CGRect(origin: CGPoint(x: 20, y: 20), size: exactLabelsize)
Risposto il 01/03/2017 a 13:27
fonte dall'utente

voti
2

Swift 2:

    yourLabel.text = "your very long text"
    yourLabel.numberOfLines = 0
    yourLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    yourLabel.frame.size.width = 200
    yourLabel.frame.size.height = CGFloat(MAXFLOAT)
    yourLabel.sizeToFit()

Le linee interessanti sono sizeToFit()in congiunzione con la fissazione di un frame.size.heightal galleggiante massimo, questo darà spazio per il testo a lungo, ma sizeToFit()si costringeranno ad utilizzare solo il necessario, ma sempre lo chiamano dopo aver impostato il .frame.size.height.

Mi consiglia di impostare un .backgroundColora scopo di debug, in questo modo è possibile visualizzare la cornice viene eseguito il rendering per ogni caso.

Risposto il 26/11/2015 a 18:51
fonte dall'utente

voti
2

È possibile utilizzare come metodo, pure. @Pyjamasam è molto vero in modo da sto solo facendo il suo metodo. Può essere utile per qualcun altro

-(CGRect)setDynamicHeightForLabel:(UILabel*)_lbl andMaxWidth:(float)_width{
    CGSize maximumLabelSize = CGSizeMake(_width, FLT_MAX);

    CGSize expectedLabelSize = [_lbl.text sizeWithFont:_lbl.font constrainedToSize:maximumLabelSize lineBreakMode:_lbl.lineBreakMode];

    //adjust the label the the new height.
    CGRect newFrame = _lbl.frame;
    newFrame.size.height = expectedLabelSize.height;
    return newFrame;
}

e appena impostato in questo modo

label.frame = [self setDynamicHeightForLabel:label andMaxWidth:300.0];
Risposto il 20/01/2014 a 13:19
fonte dall'utente

voti
2
UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 10,100, 200.0f)];
itemTitle.text = @"aseruy56uiytitfesh";
itemTitle.adjustsFontSizeToFitWidth = NO;
itemTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
itemTitle.font = [UIFont boldSystemFontOfSize:18.0];
itemTitle.textColor = [UIColor blackColor];
itemTitle.shadowColor = [UIColor whiteColor];
itemTitle.shadowOffset = CGSizeMake(0, 1);
itemTitle.backgroundColor = [UIColor blueColor];
itemTitle.lineBreakMode = UILineBreakModeWordWrap;
itemTitle.numberOfLines = 0;
[itemTitle sizeToFit];
[self.view addSubview:itemTitle];

utilizzare questo qui tutte le proprietà sono utilizzate sull'etichetta e provarlo aumentando il testo nella itemTitle.text come

itemTitle.text = @"diofgorigjveghnhkvjteinughntivugenvitugnvkejrfgnvkhv";

mostrerà la risposta Perfetc di cui hai bisogno

Risposto il 27/06/2013 a 13:02
fonte dall'utente

voti
2

Grazie per questo post. Mi ha aiutato molto. Nel mio caso sto anche la modifica del testo in un controller vista separata. Ho notato che quando uso:

[cell.contentView addSubview:cellLabel];

nel tableView: cellForRowAtIndexPath: metodo che l'etichetta è stata vista continuamente reso sopra la parte superiore della vista precedente ogni volta ho modificato la cella. Il testo è diventato pixel, e quando qualcosa è stato eliminato o modificato, la versione precedente era visibile sotto la nuova versione. Ecco come ho risolto il problema:

if ([[cell.contentView subviews] count] > 0) {
    UIView *test = [[cell.contentView subviews] objectAtIndex:0];
    [test removeFromSuperview];
}
[cell.contentView insertSubview:cellLabel atIndex:0];

Non stratificazione più strano. Se c'è un modo migliore per gestire questa situazione, per favore fatemelo sapere.

Risposto il 20/02/2009 a 23:54
fonte dall'utente

voti
1

Estensione UILabel sulla base di questa risposta per Swift 4 e superiori

extension UILabel {

    func retrieveTextHeight () -> CGFloat {
        let attributedText = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:self.font])

        let rect = attributedText.boundingRect(with: CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

        return ceil(rect.size.height)
    }

}

Può essere usato come:

self.labelHeightConstraint.constant = self.label.retrieveTextHeight()
Risposto il 31/10/2017 a 13:00
fonte dall'utente

voti
1

Aggiungendo alle risposte di cui sopra:

Ciò può essere ottenuto facilmente tramite storyboard.

  1. Impostare vincolo per UILabel. (Nel mio caso ho in alto, a sinistra ea larghezza fissa)
  2. Set Numero della linea a 0 in ispettore Attributo
  3. Impostare Interruzione di riga di WordWrap in ispettore attributo.

UILabel Altezza Regolare

Risposto il 18/10/2017 a 22:10
fonte dall'utente

voti
1

Il mio approccio per calcolare l'altezza dinamica di UILabel.

    let width = ... //< width of this label 
    let text = ... //< display content

    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.preferredMaxLayoutWidth = width

    // Font of this label.
    //label.font = UIFont.systemFont(ofSize: 17.0)
    // Compute intrinsicContentSize based on font, and preferredMaxLayoutWidth
    label.invalidateIntrinsicContentSize() 
    // Destination height
    let height = label.intrinsicContentSize.height

Avvolgere alla funzione:

func computeHeight(text: String, width: CGFloat) -> CGFloat {
    // A dummy label in order to compute dynamic height.
    let label = UILabel()

    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.font = UIFont.systemFont(ofSize: 17.0)

    label.preferredMaxLayoutWidth = width
    label.text = text
    label.invalidateIntrinsicContentSize()

    let height = label.intrinsicContentSize.height
    return height
}
Risposto il 19/07/2017 a 06:02
fonte dall'utente

voti
1
myLabel.text = "your very long text"
myLabel.numberOfLines = 0
myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

Si prega di impostare vincoli per UILable in storyboard tra cui in alto a destra in basso a sinistra

Risposto il 21/01/2017 a 09:07
fonte dall'utente

voti
1

Questo metodo darà perfetta altezza

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
CGSize constraint = CGSizeMake(width , 20000.0f);
CGSize title_size;
float totalHeight;


title_size = [text boundingRectWithSize:constraint
                                options:NSStringDrawingUsesLineFragmentOrigin
                             attributes:@{ NSFontAttributeName : font }
                                context:nil].size;

totalHeight = ceil(title_size.height);

CGFloat height = MAX(totalHeight, 40.0f);
return height;
}
Risposto il 07/04/2016 a 14:00
fonte dall'utente

voti
1

Il mio codice:

UILabel *label      = [[UILabel alloc] init];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text          = text;
label.textAlignment = NSTextAlignmentCenter;
label.font          = [UIFont fontWithName:_bodyTextFontFamily size:_bodyFontSize];

CGSize size = [label sizeThatFits:CGSizeMake(width, MAXFLOAT)];


float height        = size.height;
label.frame         = CGRectMake(x, y, width, height);
Risposto il 08/06/2015 a 06:51
fonte dall'utente

voti
1
NSString *str = @"Please enter your text......";
CGSize lblSize = [str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize: CGSizeMake(200.0f, 600.0f) lineBreakMode: NSLineBreakByWordWrapping];

UILabel *label = [[UILabel alloc]init];
label.frame = CGRectMake(60, 20, 200, lblSize.height);
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font = [UIFont systemFontOfSize:15];
label.text = str;
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
[self.view addSubview:label];
Risposto il 29/04/2015 a 07:13
fonte dall'utente

voti
1
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cellIdentifier = @"myCell";
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell.myUILabel.lineBreakMode = UILineBreakModeWordWrap;        
    cell.myUILabel.numberOfLines = 0;
    cell.myUILabel.text = @"Some very very very very long text....."
    [cell.myUILabel.criterionDescriptionLabel sizeToFit];    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    CGFloat rowHeight = cell.myUILabel.frame.size.height + 10;

    return rowHeight;    
}
Risposto il 29/08/2012 a 08:29
fonte dall'utente

voti
1

Una linea è la risposta di Chris è sbagliata.

newFrame.size.height = maximumLabelSize.height;

dovrebbe essere

newFrame.size.height = expectedLabelSize.height;

Oltre a questo, è la soluzione corretta.

Risposto il 21/05/2009 a 07:31
fonte dall'utente

voti
1

Infine, ha funzionato. Grazie ragazzi.

Non ero a farla funzionare, perché stavo cercando di ridimensionare l'etichetta nel heightForRowAtIndexPathmetodo:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

e (sì stupido me), mi è stato il ridimensionamento l'etichetta di default nel cellForRowAtIndexPathmetodo - stavo trascurando il codice che avevo scritto in precedenza:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Risposto il 16/01/2009 a 08:25
fonte dall'utente

voti
0

È possibile ottenere l'altezza usando qui sotto code

Devi passare

  1. 2. testo carattere larghezza 3. etichetta

    func heightForLabel(text: String, font: UIFont, width: CGFloat) -> CGFloat {
    
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()
    
    return label.frame.height
    }
    
Risposto il 12/04/2018 a 10:43
fonte dall'utente

voti
0

Il problema è che nessuno di funzioni indicate è attendibile e per qualche stringa e il carattere restituirà valore di altezza errato. Soprattutto non riuscirà per i testi attribuiti.

L'unica soluzione realiable è qui: https://stackoverflow.com/a/4214978/699944 e il punto è quello di utilizzare CoreText calcolare manualmente l'altezza di ogni linea per ottenere giusta dimensione. Non c'è altro modo conosciuto per fare questo.

Risposto il 28/01/2014 a 09:55
fonte dall'utente

voti
0

Questo metodo funziona sia per iOS 6 e 7

- (float)heightForLabelSize:(CGSize)maximumLabelSize  Font:(UIFont *)font String:(NSString*)string {

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
    NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:font forKey: NSFontAttributeName];

    CGSize adjustedLabelSize = [string maximumLabelSize
                                                                  options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
                                                               attributes:stringAttributes context:nil].size;
    return adjustedLabelSize.height;
}
else {
    CGSize adjustedLabelSize = [string sizeWithFont:font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];

    return adjustedLabelSize.height;
}

}
Risposto il 17/01/2014 a 15:55
fonte dall'utente

voti
-1

Quando autoLayout è attivato il ridimensionamento non funziona :)

Risposto il 09/10/2013 a 03:07
fonte dall'utente

voti
-2

Aggiornamenti secondo iOS7

// If description are available for protocol
protocolDescriptionLabel.text = [dataDictionary objectForKey:@"description"];
[protocolDescriptionLabel sizeToFit];
[protocolDescriptionLabel setLineBreakMode:NSLineBreakByWordWrapping];

CGSize expectedLabelSize = [protocolDescriptionLabel
               textRectForBounds:protocolDescriptionLabel.frame
               limitedToNumberOfLines:protocolDescriptionLabel.numberOfLines].size;
NSLog(@"expectedLabelSize %f", expectedLabelSize.height);

//adjust the label the the new height.
CGRect newFrame = protocolDescriptionLabel.frame;
newFrame.size.height = expectedLabelSize.height;
protocolDescriptionLabel.frame = newFrame;
Risposto il 13/11/2013 a 08:51
fonte dall'utente

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more