简体   繁体   中英

uilabel text with new line only when required

this is what i am using:

it works if address, city, zip.....length >0.(these field may grow in future)

self.addressInfoLbl.text = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@", address, city, zip, state, country];(numberofline == 0)

but if any of them length =0 then i got unnecessary new line. i am working on manually preparing(appending \\n).if there are more and more fields then doing it manuallt is really hard. Is there any other proper way.Am i doing it right.

Thanks

Try following code. It creates array of your strings, removes empty strings and then concatenates them with componentsJoinedByString :

NSArray *strings = @[address, city, zip, state, country];
strings = [strings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
NSString *resultString = [strings componentsJoinedByString:@"\n"];

You can join an array of objects into a string with a separator:

NSArray *props = [NSArray arrayWithObjects: address, city, state, nil];
NSString *joinedString = [props componentsJoinedByString:@"\n"];

and you will get:

"6th avenue\nAtlanta\nGeorgia"

If you don't know the amount of properties, use NSMutableArray instead of NSArray and add your properties at runtime.

try this code, it not optimal but it can resolve youy issue

NSArray *arr = [NSArray arrayWithObjects: @"address", @"", @"state", nil];
NSString *addressInfo = @"";
for (NSString *str in arr) {
    if (str.length > 0) {
       addressInfo = [addressInfo stringByAppendingString:[NSString stringWithFormat:@"\n%@", str]];
    }
}
if (addressInfo && ![@"" isEqualToString:addressInfo])
    addressInfo = [addressInfo substringFromIndex:1];
NSLog(@"address Info = %@", addressInfo);

Try this once,

NSMutableString *joinedString=[NSMutableString string];
NSArray *arr = [NSArray arrayWithObjects: address, city, state, nil];
for(NSString *str in arr)
{
    if([str length]>0) [joinedString appendFormat:@"\n%@", str];
}

NSString *resultString=[joinedString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", resultString);
Lbl.numberOfLines=0;
Lbl.lineBreakMode=NSLineBreakByCharWrapping;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM