在iPhone中使用UILineBreakModeWordWrap UILabel时访问最后一行

时间:2012-01-06 14:22:07

标签: iphone ios xcode uilabel

我使用UILabelUILineBreakModeWordWrap显示一个长字符串。它通过在UILabel中包装文本来完美地显示字符串。我想访问UILabel的最后一行。有谁知道如何在iPhone上执行此操作?

1 个答案:

答案 0 :(得分:0)

所以我尝试了一些东西并搜索了一下。你真正需要的是计算单词换行并以某种方式检测最后一个字符串。但我并没有真正意识到如何做到这一点。

所以我的解决方案是这样的:

你的字符串//I googled some longer String

 NSString *string = @"Standing across the room, I saw you smile\nSaid I want to talk to you-oo-oo for a little while\nBut before I make my move my emotions start running wild\nMy tongue gets tied and that's no lie\nLooking in your eyes\nLooking in you big brown eyes ooh yeah\nAnd I've got this to say to you\nHey!\nGirl I want to make you sweat\nSweat till you can't sweat no more\nAnd if you cry out\nI'm gonna push it some, more, more\nGirl I want to make you sweat\nSweat till you can't sweat no more\nAnd if you cry out\nI'm gonna push it\nPush it, push it some more";

您的标签:

UILabel *label          = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 280, 440)];
label.font              = [UIFont fontWithName:@"Helvetica" size:14];
label.lineBreakMode     = UILineBreakModeWordWrap;
label.numberOfLines     = 0;
label.backgroundColor   = [UIColor clearColor];
label.textColor         = [UIColor blackColor];
label.text              = string;

调用此方法:

NSString *result = [self getLastLineFromString:string];
NSLog(@"Result: %@", result);

getLastLineFromString:看起来像这样:

- (NSString *)getLastLineFromString: (NSString *)string{
    NSArray *a = [string componentsSeparatedByString:@" "];
    NSString *result = [a objectAtIndex:[a count]-1];
    NSString *temp = @"";
    int count = 1;
    BOOL myBool = YES;
    while (myBool) {
        count++;

        temp = result;
        result = [a objectAtIndex:[a count] -count];
        result = [NSString stringWithFormat:@"%@ %@", result, temp];
        NSLog(@"length: %i",[self lengthOfString:result]);
        NSLog(@"result: %@",result);

    //131 was a value i detected mayels, i guess u have do trick a little around to find a mathcing one for yourself
    if ([self lengthOfString:result] >= 131) {
        myBool = NO;
    }
    }
    return result;
}

方法lengthOfString:如下所示:

- (int)lengthOfString:(NSString *)string{
    CGSize size1 = [string sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14]];
    return size1.width;
}

输出:

2012-01-06 16:17:08.341 get length[5472:207] result: it
Push it, push it some more

我知道这不是一个完美的解决方案,但它可能对你有帮助。