I have a UILabel
and in some cases the text is longer then the UILabel
itself, so I see the text as "bla bla bla..."
I want to add a ...Read More
button text at the end of the UILabel
..
I've read some posts but they offer solutions that are not good to me, for example: to calculate how many characters will enter the UILabel
, but with the font i'm using each character has a different width.
How can I manage to do that?
Thanks in advance!
So this is what I did to add the Read More... button to the UITextView
, UITextField
or UILabel
:
- (void)addReadMoreStringToUILabel:(UILabel*)label
{
NSString *readMoreText = @" ...Read More";
NSInteger lengthForString = label.text.length;
if (lengthForString >= 30)
{
NSInteger lengthForVisibleString = [self fitString:label.text intoLabel:label];
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
}];
NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:@{
NSFontAttributeName : Font(TWRegular, 12.),
NSForegroundColorAttributeName : White
}];
[answerAttributed appendAttributedString:readMoreAttributed];
label.attributedText = answerAttributed;
UITagTapGestureRecognizer *readMoreGesture = [[UITagTapGestureRecognizer alloc] initWithTarget:self action:@selector(readMoreDidClickedGesture:)];
readMoreGesture.tag = 1;
readMoreGesture.numberOfTapsRequired = 1;
[label addGestureRecognizer:readMoreGesture];
label.userInteractionEnabled = YES;
}
else {
NSLog(@"No need for 'Read More'...");
}
}
There is a use of fitString:intoLabel
method which can be found here.
As for the UITagTapGestureRecognizer
is just a normal UITapGestureRecognizer
subclass with a NSInteger
property called tag. I did that because I want to identify which Read More...
were clicked in I case I have more than one in the same UIViewController
. You can use a normal UITapGestureRecognizer
.
Enjoy!