C'è un modo per avere più righe di testo UILabelcome nel UITextViewo dovrei usare la seconda invece?
C'è un modo per avere più righe di testo UILabelcome nel UITextViewo dovrei usare la seconda invece?
Risposte:
Ho trovato una soluzione
Basta aggiungere il seguente codice:
// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0
// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0
// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;
// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;
Vecchia risposta ripristinata (per riferimento e sviluppatori disposti a supportare iOS sotto 6.0):
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;
A parte: entrambi i valori di enum cedono 0comunque.
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrappingecell.textLabel?.numberOfLines = 0
In IB, impostare il numero di righe su 0 (consente righe illimitate)
Quando si digita all'interno del campo di testo utilizzando IB, utilizzare "alt-return" per inserire un ritorno e passare alla riga successiva (oppure è possibile copiare nel testo già separato da linee).
La migliore soluzione che ho trovato (a un problema altrimenti frustrante che avrebbe dovuto essere risolto nel quadro) è simile a quella di Vaychick.
Basta impostare il numero di righe su 0 in IB o codice
myLabel.numberOfLines = 0;
Questo visualizzerà le linee necessarie ma riposizionerà l'etichetta in modo che sia centrata orizzontalmente (in modo che un'etichetta di 1 linea e 3 linee siano allineate nella loro posizione orizzontale). Per risolvere il problema, aggiungi:
CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode];
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;
myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];
Se devi usare:
myLabel.numberOfLines = 0;
È inoltre possibile utilizzare un'interruzione di riga standard ("\n"), nel codice, per forzare una nuova riga.
proviamo questo
textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated
textLabel.numberOfLines = 0;
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;
La soluzione sopra non funziona nel mio caso. Sto facendo così:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ...
CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap];
return size.height + 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
// ...
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"Georgia-Bold" size:18.0];
}
// ...
UILabel *textLabel = [cell textLabel];
CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0]
constrainedToSize:CGSizeMake(240.0, 480.0)
lineBreakMode:UILineBreakModeWordWrap];
cell.textLabel.frame = CGRectMake(0, 0, size.width + 20, size.height + 20);
//...
}
Usa story borad: seleziona l'etichetta per impostare il numero di righe su zero ...... Oppure fai riferimento a questo
Swift 3
Imposta il numero di righe zero per informazioni di testo dinamiche, sarà utile per variare il testo.
var label = UILabel()
let stringValue = "A label\nwith\nmultiline text."
label.text = stringValue
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
label.minimumScaleFactor = 0.8 . // It is not required but nice to have a minimum scale factor to fit text into label frame

UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;
helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;
Per alcuni motivi non funziona per me in iOS 6 non so perché. Ho provato con e senza testo attribuito. Eventuali suggerimenti.
Prova a usare questo:
lblName.numberOfLines = 0;
[lblName sizeToFit];
Queste cose mi hanno aiutato
Modifica queste proprietà di UILabel
label.numberOfLines = 0;
label.adjustsFontSizeToFitWidth = NO;
label.lineBreakMode = NSLineBreakByWordWrapping;
E mentre dai l'input String usa \ n per visualizzare parole diverse su righe diverse.
Esempio :
NSString *message = @"This \n is \n a demo \n message for \n stackoverflow" ;
Metodo 1:
extension UILabel {//Write this extension after close brackets of your class
func lblFunction() {
numberOfLines = 0
lineBreakMode = .byWordWrapping//If you want word wraping
//OR
lineBreakMode = .byCharWrapping//If you want character wraping
}
}
Adesso chiama semplicemente così
myLbl.lblFunction()//Replace your label name
EX:
Import UIKit
class MyClassName: UIViewController {//For example this is your class.
override func viewDidLoad() {
super.viewDidLoad()
myLbl.lblFunction()//Replace your label name
}
}//After close of your class write this extension.
extension UILabel {//Write this extension after close brackets of your class
func lblFunction() {
numberOfLines = 0
lineBreakMode = .byWordWrapping//If you want word wraping
//OR
lineBreakMode = .byCharWrapping//If you want character wraping
}
}
Metodo 2:
programmazione
yourLabel.numberOfLines = 0
yourLabel.lineBreakMode = .byWordWrapping//If you want word wraping
//OR
yourLabel.lineBreakMode = .byCharWrapping//If you want character wraping
Metodo 3:
Attraverso la scheda Story
Per visualizzare più righe impostate 0 (zero), verrà visualizzata più di una riga nell'etichetta.
Se si desidera visualizzare n righe, impostare n.
Vedi sotto lo schermo.
Se si desidera impostare la dimensione minima del carattere per l'etichetta Fare clic su Restringimento automatico e selezionare l'opzione Dimensione minima carattere
Vedi sotto le schermate
Qui imposta la dimensione minima del carattere
EX: 9 (In questa immagine)
Se l'etichetta ottiene più testo in quel momento, il testo dell'etichetta verrà ridotto a 9
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];
Puoi farlo anche tramite lo Storyboard:
dovresti provare questo:
-(CGFloat)dynamicLblHeight:(UILabel *)lbl
{
CGFloat lblWidth = lbl.frame.size.width;
CGRect lblTextSize = [lbl.text boundingRectWithSize:CGSizeMake(lblWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:lbl.font}
context:nil];
return lblTextSize.size.height;
}
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";
In questa funzione passare la stringa che si desidera assegnare nell'etichetta e passare la dimensione del carattere al posto di self.activityFont e passare la larghezza dell'etichetta al posto di 235, ora si ottiene l'altezza dell'etichetta in base alla stringa. funzionerà benissimo.
-(float)calculateLabelStringHeight:(NSString *)answer
{
CGRect textRect = [answer boundingRectWithSize: CGSizeMake(235, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.activityFont} context:nil];
return textRect.size.height;
}
Impostare di seguito nel codice o nello storyboard stesso
Label.lineBreakMode = NSLineBreakByWordWrapping; Label.numberOfLines = 0;
e non dimenticare di impostare i vincoli sinistro, destro, superiore e inferiore per l'etichetta, altrimenti non funzionerà.
Swift 4:
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.preferredMaxLayoutWidth = superview.bounds.size.width - 10
Su C #, questo ha funzionato per me all'interno di UITableViewCell.
UILabel myLabel = new UILabel();
myLabel.Font = UIFont.SystemFontOfSize(16);
myLabel.Lines = 0;
myLabel.TextAlignment = UITextAlignment.Left;
myLabel.LineBreakMode = UILineBreakMode.WordWrap;
myLabel.MinimumScaleFactor = 1;
myLabel.AdjustsFontSizeToFitWidth = true;
myLabel.InvalidateIntrinsicContentSize();
myLabel.Frame = new CoreGraphics.CGRect(20, mycell.ContentView.Frame.Y + 20, cell.ContentView.Frame.Size.Width - 40, mycell.ContentView.Frame.Size.Height);
myCell.ContentView.AddSubview(myLabel);
Penso che il punto qui sia: -
myLabel.TextAlignment = UITextAlignment.Left;
myLabel.LineBreakMode = UILineBreakMode.WordWrap;
myLabel.MinimumScaleFactor = 1;
myLabel.AdjustsFontSizeToFitWidth = true;
Questo codice restituisce l'altezza delle dimensioni in base al testo
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
{
CGFloat result = font.pointSize+4;
if (text)
{
CGSize size;
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+1);
result = MAX(size.height, result); //At least one row
}
return result;
}
UILineBreakModeWordWrapstato deprecato in iOS 6. Ora dovresti usareNSLineBreakByWordWrapping = 0Vedi la documentazione qui