如何设置 UILabel 的最大长度?
How to set maximum length for UILabel?
在 Objective-C
中,我试图为 UILabel
设置字符长度限制,但我找不到任何方法。比如在UILabel
里面输入了一行文字,比如说100,但是如果最大字符长度设置为50,我只想让它恰好在50处截断,甚至不截断。我只是想让它在达到极限时切断。
这个我试过了;但它没有用:
NSString *string = my_uilabelText;
if ([string length] >74) {
string = [string substringToIndex:74];
}
任何见解或帮助将不胜感激。谢谢
根据您的评论,您实际实施的内容是可行的。你只需要确保你的语法是正确的。
假设您从数据库中获取字符串:
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
before 它被委托
调用
在 Objective-C
中,我试图为 UILabel
设置字符长度限制,但我找不到任何方法。比如在UILabel
里面输入了一行文字,比如说100,但是如果最大字符长度设置为50,我只想让它恰好在50处截断,甚至不截断。我只是想让它在达到极限时切断。
这个我试过了;但它没有用:
NSString *string = my_uilabelText;
if ([string length] >74) {
string = [string substringToIndex:74];
}
任何见解或帮助将不胜感激。谢谢
根据您的评论,您实际实施的内容是可行的。你只需要确保你的语法是正确的。
假设您从数据库中获取字符串:
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
before 它被委托