作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我必须在 uilabel 的一定限制后使用显示更多文本。当我点击那个 uilabel show more text 标签应该展开并且 show more text 应该改变为 show less 。
最佳答案
使用以下代码作为答案。
- (void)addReadMoreStringToUILabel:(UILabel*)label
{
NSString *readMoreText = @" ...Read More";
NSInteger lengthForString = label.text.length;
if (lengthForString >= 100)
{
NSInteger lengthForVisibleString = 100;
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:label.text];
NSString *trimmedString = [mutableString stringByReplacingCharactersInRange:NSMakeRange(lengthForVisibleString, (label.text.length - lengthForVisibleString)) withString:@""];
NSInteger readMoreLength = readMoreText.length;
NSString *trimmedForReadMore = [trimmedString stringByReplacingCharactersInRange:NSMakeRange((trimmedString.length - readMoreLength), readMoreLength) withString:@""];
NSMutableAttributedString *answerAttributed = [[NSMutableAttributedString alloc] initWithString:trimmedForReadMore attributes:@{
NSFontAttributeName : label.font
}];
UIColor *color = [UIColor colorWithRed:21.0/255.0 green:40.0/255.0 blue:86.0/255.0 alpha:1]; // select needed color
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color, NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)};
NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:attrs];
[answerAttributed appendAttributedString:readMoreAttributed];
label.attributedText = answerAttributed;
UITapGestureRecognizer *readMoreGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(readMoreDidClickedGesture:)];
readMoreGesture.numberOfTapsRequired = 1;
[label addGestureRecognizer:readMoreGesture];
label.userInteractionEnabled = YES;
}
else
{
NSLog(@"No need for 'Read More'...");
}
}
-(void)readMoreDidClickedGesture:(id)sender
{
if(ReadMoretag==1)
{
ReadMoretag=0;
NSString *readMoreText = @" Read Less";
UIColor *color = [UIColor colorWithRed:21.0/255.0 green:40.0/255.0 blue:86.0/255.0 alpha:1]; // select needed color
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:attrs];
NSMutableAttributedString *answerAttributed = [[NSMutableAttributedString alloc] initWithString:StrProfileSummary attributes:@{
NSFontAttributeName : LblProfilEsummary.font
}];
[answerAttributed appendAttributedString:readMoreAttributed];
LblProfilEsummary.attributedText = answerAttributed;
}
else
{
ReadMoretag=1;
[self addReadMoreStringToUILabel:LblProfilEsummary];
}
}
关于ios - 如何在 uilabel 中显示 "Show more"文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44817585/
我是一名优秀的程序员,十分优秀!