如何限制UILabel文本长度 - IOS
是否有可能限制文本的长度为UILabel ..我知道我可以限制字符串无论我分配标签,但我只需要知道...是否有任何可能性在UILabel级别做到这一点?如何限制UILabel文本长度 - IOS
在我来说,我只是想只显示10个字符的UILabel ..
NSString *temp = your string;
if ([temp length] > 10) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 10}];
temp = [temp substringWithRange:range];
}
coverView.label2.text = temp;
是的,你可以使用:
your_text = [your_text substringToIndex:10];
your_label.text = your_text;
希望它可以帮助你。此外,通过改变constrainedToSize的价值
NSString *[email protected]"Your Text to be shown";
CGSize textSize=[string sizeWithFont:[UIFont fontWithName:@"Your Font Name"
size:@"Your Font Size (in float)"]
constrainedToSize:CGSizeMake(100,50)
lineBreakMode:NSLineBreakByTruncatingTail];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 50,textSize.width, textSize.height)];
[myLabel setLineBreakMode:NSLineBreakByTruncatingTail];
[myLabel setText:string];
:您可以修复的UILabel
的最大尺寸它可能会起作用,但它会将整个标签大小缩减为其字符串长度,在我的情况下,我在标签的右端添加了一些视图,但不应该受到干扰,因此我只需要限制文本而不是整个标签。 – Newbee 2013-05-04 05:48:30
我看不到任何直接的方式来实现这一目标。但是,我们可以做一些事情,让我们做一个category为UILabel
@interface UILabel(AdjustSize)
- (void) setText:(NSString *)text withLimit : (int) limit;
@end
@implementation UILabel(AdjustSize)
- (void) setText:(NSString *)text withLimit : (int) limit{
text = [text substringToIndex:limit];
[self setText:text];
}
@end
你可以把它在你的类要做到这一点(或使其在单独的扩展类,并导入需要此功能);
现在使用在以下方式:
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectZero];
[lbl setText:@"Hello Newbee how are you?" withLimit:10];
NSLog(@"lbl.text = %@", lbl.text);
这里是日志:
2013年5月9日15:43:11.077 FreakyLabel [5925:11303] lbl.text =你好福利局
请更新我与downvote的原因。 – rptwsthi 2014-07-03 15:28:18
我固定这通过添加viewDidLoad中的通知:侦听当长度超过一个值:
- (void)limitLabelLength {
if ([self.categoryField.text length] > 15) {
// User cannot type more than 15 characters
self.categoryField.text = [self.categoryField.text substringToIndex:15];
}
}
你的代码为我工作:) – 2015-09-26 09:13:01
太棒了!如果你还没有做过,记得投票答复。 – 2015-12-15 09:02:41
是的,已经完成 – 2015-12-15 09:42:49
你可以尝试'[labelText substringToIndex:10];' – Anupdas 2013-05-04 05:40:05
你不能直接告诉标签只显示10个字符,我知道下面的答案不是你要求的,但他们是唯一的可能性来限制字符串显示标签。 – HAS 2013-05-04 15:58:24