如何设置UILabel的最大长度?

时间:2015-08-30 23:57:07

标签: ios objective-c uilabel

Objective-C中,我试图为UILabel设置字符长度限制,但我找不到任何方法。例如,一行文本输入到UILabel,比如100,但如果最大字符长度设置为50,我只是希望它精确地切断50,甚至不截断。我只是想在它达到极限时切断它。

我试过这个;但它没有用:

 NSString *string = my_uilabelText; 
 if ([string length] >74) { 
    string = [string substringToIndex:74]; 
 } 

非常感谢任何见解或帮助。谢谢

1 个答案:

答案 0 :(得分:0)

根据您的评论,您实际实施的内容将起作用。您只需确保语法正确。

假设您从数据库中获取字符串:

NSString *string = stringFromDatabase;
//execute your conditional if statement
if (string.length > 50) { //meaning 51+
    /* trim the string. Its important to note that substringToIndex returns a
    new string containing the characters of the receiver up to, but not 
    including, the one at a given index. In other words, it goes up to 50, 
    but not 50, so that means we have to do desired number + 1. 
    Additionally, this method includes counting white-spaces */

    string = [string substringToIndex:51];
}

然后我们必须设置标签文本,这不会自动发生。完全如此:

NSString *string = stringFromDatabase;
if (string.length > 50) { 
    string = [string substringToIndex:51];
}
self.someUILabel.text = string;

我认为你这样做的方式可能不是用户友好的。您将获得已设置文本的UILabel字符串,然后重置它。 相反,您应该在代理人调用之前将所需的文字设置为UILabel