在Objective-C
中,我试图为UILabel
设置字符长度限制,但我找不到任何方法。例如,一行文本输入到UILabel
,比如100,但如果最大字符长度设置为50,我只是希望它精确地切断50,甚至不截断。我只是想在它达到极限时切断它。
我试过这个;但它没有用:
NSString *string = my_uilabelText;
if ([string length] >74) {
string = [string substringToIndex:74];
}
非常感谢任何见解或帮助。谢谢
答案 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