Code Monkey home page Code Monkey logo

responsivelabel's Introduction

Version License Platform

#ResponsiveLabel A UILabel subclass which responds to touch on specified patterns. It has the following features:

  1. It can detect pattern specified by regular expression and apply style like font, color etc.
  2. It allows to replace default ellipse with tappable attributed string to mark truncation
  3. Convenience methods are provided to detect hashtags, username handler and URLs

#Installation

Add following lines in your pod file
pod 'ResponsiveLabel', '~> 1.0.11'

#Usage

The following snippets explain the usage of public methods. These snippets assume an instance of ResponsiveLabel named "customLabel".

#import <ResponsiveLabel.h>

In interface builder, set the custom class of your UILabel to ResponsiveLabel. You may get an error message saying "error: IB Designables: Failed to update auto layout status: Failed to load designables from path (null)" This appears to be an issue with Xcode and Cocoapods and does not seem to cause any problems, but some have been able to fix it, see this Stackoverflow question for more details.

Pattern Detection

//Detects email in text
NSString *emailRegexString = @"[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
NSError *error;
NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:emailRegexString
options:0
error:&error];
PatternDescriptor *descriptor = [[PatternDescriptor alloc]initWithRegex:regex withSearchType:PatternSearchTypeAll 
withPatternAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
[self.customLabel enablePatternDetection:descriptor];

String Detection

self.customLabel.userInteractionEnabled = YES;
PatternTapResponder tapResponder = ^(NSString *string) {
    NSLog(@"tapped = %@",string);
};
[self.customLabel enableStringDetection:@"text" withAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],
                                                                 RLTapResponderAttributeName: tapResponder}];

Array of String Detection

self.customLabel.userInteractionEnabled = YES;
PatternTapResponder stringTapAction = ^(NSString *tappedString) {
    NSLog(@"tapped string = %@",tappedString);
  };
[self.customLabel enableDetectionForStrings:@[@"text",@"long"] withAttributes:@{NSForegroundColorAttributeName:[UIColor brownColor],
                                                                                  RLTapResponderAttributeName:stringTapAction}];

HashTag Detection

self.customLabel.userInteractionEnabled = YES;
PatternTapResponder hashTagTapAction = ^(NSString *tappedString) {
NSLog(@"HashTag Tapped = %@",tappedString);
};
[self.customLabel enableHashTagDetectionWithAttributes:
@{NSForegroundColorAttributeName:[UIColor redColor], RLTapResponderAttributeName:hashTagTapAction}];

Username Handle Detection

self.customLabel.userInteractionEnabled = YES;
PatternTapResponder userHandleTapAction = ^(NSString *tappedString){
NSLog(@"Username Handler Tapped = %@",tappedString);
};
[self.customLabel enableUserHandleDetectionWithAttributes:
@{NSForegroundColorAttributeName:[UIColor grayColor],RLTapResponderAttributeName:userHandleTapAction}];

URL Detection

self.customLabel.userInteractionEnabled = YES;
PatternTapResponder urlTapAction = ^(NSString *tappedString) {
NSLog(@"URL Tapped = %@",tappedString);
};
[self.customLabel enableURLDetectionWithAttributes:
@{NSForegroundColorAttributeName:[UIColor cyanColor],NSUnderlineStyleAttributeName:[NSNumber
numberWithInt:1],RLTapResponderAttributeName:urlTapAction}];

Highlight Patterns On Tap

To highlight patterns, one can set the attributes:

  • RLHighlightedForegroundColorAttributeName
  • RLHighlightedBackgroundColorAttributeName
  • RLHighlightedBackgroundCornerRadius
self.customLabel.userInteractionEnabled = YES;
PatternTapResponder userHandleTapAction = ^(NSString *tappedString){
NSLog(@"Username Handler Tapped = %@",tappedString);
};
[self.customLabel enableUserHandleDetectionWithAttributes:
@{NSForegroundColorAttributeName:[UIColor grayColor],RLHighlightedForegroundColorAttributeName:[UIColor greenColor],RLHighlightedBackgroundCornerRadius:@5,RLHighlightedBackgroundColorAttributeName:[UIColor blackColor],RLTapResponderAttributeName:userHandleTapAction}];

Custom Truncation Token

Set attributed string as truncation token
Deprecated in 1.0.10
NSString *expansionToken = @"Read More ...";
NSString *str = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:kExpansionToken attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:self.customLabel.font}];
[self.customLabel setAttributedTruncationToken:attribString withAction:^(NSString *tappedString) {
NSLog(@"Tap on truncation text");
}];
[self.customLabel setText:str withTruncation:YES];
Latest introduced on 1.0.10
NSString *expansionToken = @"Read More ...";
NSString *str = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
PatternTapResponder tap = ^(NSString *string) {
   NSLog(@"Tap on truncation text");
  }
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:kExpansionToken attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:self.customLabel.font,RLTapResponderAttributeName:tap}];
[self.customLabel setAttributedTruncationToken:attribString];
[self.customLabel setText:str withTruncation:YES];
Set image as truncation token

The height of image size should be approximately equal to or less than the font height. Otherwise the image will not be rendered properly

[self.customLabel setTruncationIndicatorImage:[UIImage imageNamed:@"more_image"] withSize:CGSizeMake(25, 5) andAction:^(NSString *tappedString) {
    NSLog(@"tapped on image");
 }];
Set from interface builder

Screenshots

References

The underlying implementation of ResponsiveLabel is based on KILabel(https://github.com/Krelborn/KILabel). ResponsiveLabel is made flexible to enable detection of any pattern specified by regular expression.

The following articles were helpful in enhancing the functionalities.

responsivelabel's People

Contributors

andreyoshev avatar georgesteiner avatar hsusmita avatar m-ricca avatar thelastjedi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

responsivelabel's Issues

Truncation token set from interface builder does not show

I am trying to set the truncation token in IB, but I do not have width/height constraints. I have top, bottom, left, right constraints instead. The UILabel is set to be a ResponsiveLabel, number of lines = 0.

The token shows in IB, but not when the app runs

Any ideas?

IBOutlet issue

Hello,

I am trying to add Responsive label in xib. But xib is giving error:

screen shot 2018-08-10 at 12 22 54 pm

Also if I select Inherit Module from Target xib is not giving error but app is crashing. Because it considered label as UILabel than Responsive Label.

screen shot 2018-08-10 at 12 23 27 pm

ResponsiveLabel not updating correctly in UITableView

I have a UITableViewCell in which I am using two separate ResponsiveLabel. When I scroll through the table the ResponsiveLabel is repeating text from pervious cells. I have checked that the text being set in the fields was the correct text. My logging appears to show that this is not the problem. I then started looking at where the various draw methods are being called, and this leads me to believe that the issue is with the ResponsiveLabel. It appears that even though the text is being correctly set from the model, the ResponsiveLabelโ€™s draw method is being called before the text is set in the ResponsiveLabel. My logging is currently showing that the ResponsiveLabelโ€™s text is often null when the cell is being draw.
Using the current version of ResponsiveLabel 1.0.5

Change the font for the first match

I'm facing a problem when the sentece has same words.
eg:
Username "a"
sentence: "a": i have "a" dream
i'd change the font for only the fist "a".

Does anyone knows how to do that?

Adding multiple detection like email, userhandler and url doesn't work

I add email detection, url detection and userhandler detection on same label but its not working properly.
When i add [email protected] its take @y as a userhandler detection part and chirag & .com as a url detection part. So it's not detect [email protected] as email part.

NSString *emailRegexString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSError *error;
    NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:emailRegexString
                                                                     options:0
                                                                       error:&error];
    PatternDescriptor *descriptor = [[PatternDescriptor alloc]initWithRegex:regex withSearchType:PatternSearchTypeAll
                                                      withPatternAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}];
    [self.postDetailsL enablePatternDetection:descriptor];

PatternTapResponder userHandleTapAction = ^(NSString *tappedString){
        if ([self.delegate respondsToSelector:@selector(feedCell:didTapOnUserHandle:)]) {
            [self.delegate feedCell:self didTapOnUserHandle:tappedString];
        }
    };
    [self.postDetailsL enableUserHandleDetectionWithAttributes:@{NSForegroundColorAttributeName:[UIColor blueColor], RLTapResponderAttributeName:userHandleTapAction}];

PatternTapResponder URLTapAction = ^(NSString *tappedString){
        if ([self.delegate respondsToSelector:@selector(feedNoMediaCell:didTapOnURLHandle:)]) {
            [self.delegate feedNoMediaCell:self didTapOnURLHandle:tappedString];
        }
    };
    [self.postDetailsL enableURLDetectionWithAttributes:@{NSForegroundColorAttributeName:[UIColor TARedesDisplayColor], NSUnderlineStyleAttributeName:[NSNumber numberWithInt:1], RLTapResponderAttributeName:URLTapAction}];

Crashing in table view (swift 3)

Hi Hsusmita,

I am using your ResponsiveLabel control in uitableview Language is Swift 3 and I am getting "exc_bad_access code=exc_i386_gpflt"

I am unable to debug this issue
can plz help me
I have also tried your SHResponsiveLabel but after converting it to swift 3 lots of bugs are coming
it would be great if you convert the control in Swift 3

Thanks in advance

Read more and Read less issue.

Actually i am using your library to expand/collapse UILabel in UITableViewCell. but some times when i click on "Read more" the UILabel is expand but not showing "Read less" label. so can you please help me to short out my issue. it is batter if you provide demo. here is my code that has been written in "cellForRowAtIndexPath" ..

        __block  NSString *str =mutArrEventList[indexPath.row][@"event_desc"];
        PatternTapResponder tap = ^(NSString *string) {
            NSLog(@"Tap on truncation text");

            if (![arrayOfExpandIndexPaths containsObject:indexPath]) {
                [arrayOfExpandIndexPaths addObject:indexPath];
            }

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
            });

        };



        if (![arrayOfExpandIndexPaths containsObject:indexPath]) {

             NSString *expansionToken = @"...Read more";

            NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:expansionToken attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:cell.lblDesc.font,RLTapResponderAttributeName:tap}];
            [cell.lblDesc setAttributedTruncationToken:attribString];

            cell.lblDesc.numberOfLines = 3;
            [cell.lblDesc setText:str withTruncation:YES];
        }
        else{

            NSString *expansionToken = @" Read less";

            NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:expansionToken attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:cell.lblDesc.font,RLTapResponderAttributeName:tap}];
            [cell.lblDesc setAttributedTruncationToken:attribString];


            cell.lblDesc.numberOfLines = 0;
            [cell.lblDesc setText:str withTruncation:NO];
            cell.lblDesc.customTruncationEnabled = YES;
        }

Label height with different text weight (bold and regular)

Hi, I've a problem to calculate the precise frame height for a text with different font weight.

This is the font attributes, regular weight for the normal text and bold for hashtag, screename and url.
let attributesTweet = [NSFontAttributeName : AppStyle.Fonts.get(.REGULAR, size: .SMALL)]
let attributesHighlightedTweet = [NSFontAttributeName : AppStyle.Fonts.get(.BOLD, size: .SMALL)

I need to calculate the frame height inside the table view delegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

I'm currently using boundingRectWithSize in this way:
var textHeightRequest = Utils.heightForAttributedText(request.content!, attributes: attributesHighlightedTweet, width: contentWidth)

static func heightForAttributedText(text : String, attributes : [String : AnyObject], width : Double) -> CGFloat {
    let attributedText = NSAttributedString(string: text, attributes: attributes)
    return attributedText.boundingRectWithSize(CGSize(width : width, height : DBL_MAX), options: [NSStringDrawingOptions.UsesLineFragmentOrigin, NSStringDrawingOptions.UsesFontLeading], context: nil).height
}`

This method is not accurate because I'm passing the attributesHighlightedTweet, so it's considering all the text as Bold.

I ask if there's a better way to calculate the height of the label having text with different weight.

Writing the 'enableURLDetectionWithAttributes' in cellForRowAtIndexPath stops my VC to call dealloc.

Hello Developer,

Good job on the responsive label code to detect links , below is my code in the cellForRowAtIndexPath definition snippet for reference.

Can help me why the line where the urlTapAction is assigned to enableURLDetectionWithAttributes call parameter stops my dealloc.

I have tried to put the items in background and all still doesn't works.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //Do background work
      dispatch_async(dispatch_get_main_queue(), ^{
                    
       PatternTapResponder urlTapAction = ^(NSString *tappedString) {

        [self performSelectorOnMainThread:@selector(openWebViewWithUrlString:) withObject:tappedString waitUntilDone:YES];
                      
                    };
                    
 //Update UI
 [message enableURLDetectionWithAttributes:
                     @{NSForegroundColorAttributeName:[UIColor blueColor],NSUnderlineStyleAttributeName:[NSNumber numberWithInt:1], RLTapResponderAttributeName:urlTapAction}];
                    
                });
            });

Comment this line and the dealloc gets called.

[message enableURLDetectionWithAttributes:
                     @{NSForegroundColorAttributeName:[UIColor blueColor],NSUnderlineStyleAttributeName:[NSNumber numberWithInt:1], RLTapResponderAttributeName:urlTapAction}];

Truncation token got truncated ?

When truncation token if have more than 8 character, truncation token got truncated. (screenshot 1 and screenshot 2 for compare)

screen shot 2016-05-16 at 11 35 42 am

screen shot 2016-05-16 at 11 44 32 am

for a while i solve this by add more buffer when replacing.

- (NSRange)rangeForTokenInsertionForStringWithNewLine {
    NSInteger numberOfLines, index, numberOfGlyphs = [self.layoutManager numberOfGlyphs];
    NSRange lineRange = NSMakeRange(NSNotFound, 0);
    NSInteger approximateNumberOfLines = CGRectGetHeight([self.layoutManager usedRectForTextContainer:self.textContainer])/self.font.lineHeight;
    for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++){
        [self.layoutManager lineFragmentRectForGlyphAtIndex:index
                                             effectiveRange:&lineRange];
        if (numberOfLines == approximateNumberOfLines - 1) break;
        index = NSMaxRange(lineRange);
    }
    NSRange rangeOfText = NSMakeRange(lineRange.location + lineRange.length - 3, // add more buffer
                                      self.textStorage.length - lineRange.location - lineRange.length + 1);
    return rangeOfText;
}

Is it the right solution ?

Add expanded state end token

Hi,

Here is the use case I would like to be able to achieve with the label. Have the "More" label (TruncationToken) to expand the view and a "... Less" label at the end of the text when the view is expanded and want to revert to the collapsed view.

Setting the setAttributedTruncationToken of the label after it has expanded doesn't display the "... Less" label since it's not truncated anymore.

Could you provide functionality to accomplish this?

Thank you very much for your help.

Crash while scrolling: index (X) beyond array bounds (X)

Hi!

I'm getting some random crashes when using a ResponsiveLabel inside a xib from a TableView.
When first displayed on the TableView, it goes ok, but when I scroll down, see the next row, and then scroll back to the first row, it crashes.
This happens only when the text is close to the edge of the label, for example (the pipes | denotes labels' bounds):

| this is a text @text | < fine
| this is a text that @CrashS | < not ok

Here's the log:

2015-10-03 10:05:33.926 App[2063:57122] * Terminating app due to uncaught exception 'NSRangeException', reason: '* NSRunStorage, _NSBlockNumberForIndex(): index (80) beyond array bounds (80)'
*** First throw call stack:
(
0 CoreFoundation 0x000000010c57df65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010bbd8deb objc_exception_throw + 48
2 CoreFoundation 0x000000010c57de9d +[NSException raise:format:] + 205
3 UIFoundation 0x00000001155ce94b _NSBlockNumberForIndex + 84
4 UIFoundation 0x000000011558c369 -[NSLayoutManager(NSPrivate) _invalidateGlyphsForExtendedCharacterRange:changeInLength:includeBlocks:] + 703
5 UIFoundation 0x0000000115580695 -[NSLayoutManager(NSPrivate) _fillLayoutHoleForCharacterRange:desiredNumberOfLines:isSoft:] + 1030
6 UIFoundation 0x0000000115582104 -[NSLayoutManager(NSPrivate) _fillLayoutHoleAtIndex:desiredNumberOfLines:] + 201
7 UIFoundation 0x0000000115582787 -[NSLayoutManager(NSPrivate) _markSelfAsDirtyForBackgroundLayout:] + 339
8 UIFoundation 0x000000011558ced7 -[NSLayoutManager(NSPrivate) _invalidateLayoutForExtendedCharacterRange:isSoft:invalidateUsage:] + 2106
9 UIFoundation 0x00000001155bcfea -[NSLayoutManager textStorage:edited:range:changeInLength:invalidatedRange:] + 219
10 UIFoundation 0x00000001155bd2d2 -[NSLayoutManager processEditingForTextStorage:edited:range:changeInLength:invalidatedRange:] + 47
11 UIFoundation 0x00000001155e4a76 -[NSTextStorage _notifyEdited:range:changeInLength:invalidatedRange:] + 152
12 UIFoundation 0x00000001155e4591 -[NSTextStorage processEditing] + 349
13 UIFoundation 0x00000001155e41eb -[NSTextStorage endEditing] + 82
14 Foundation 0x000000010a33b10d -[NSMutableAttributedString addAttributes:range:] + 321
15 UIFoundation 0x00000001155e69c4 __45-[NSConcreteTextStorage addAttributes:range:]_block_invoke + 267
16 UIFoundation 0x00000001155e682e -[NSConcreteTextStorage addAttributes:range:] + 109
17 App 0x000000010889803f __53-[ResponsiveLabel addAttributesForPatternDescriptor:]_block_invoke + 799
18 CoreFoundation 0x000000010c4bfd7d __53-[__NSArrayI enumerateObjectsWithOptions:usingBlock:]_block_invoke + 77
19 CoreFoundation 0x000000010c4bfc26 -[__NSArrayI enumerateObjectsWithOptions:usingBlock:] + 166
20 App 0x0000000108897cc7 -[ResponsiveLabel addAttributesForPatternDescriptor:] + 311
21 App 0x00000001088997a5 __37-[ResponsiveLabel updateTextStorage:]_block_invoke + 133
22 CoreFoundation 0x000000010c4b6466 __65-[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:]_block_invoke + 102
23 CoreFoundation 0x000000010c4b635a -[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:] + 202
24 App 0x00000001088996dc -[ResponsiveLabel updateTextStorage:] + 476
25 App 0x00000001088933e3 -[ResponsiveLabel setText:] + 275
26 App 0x00000001087fbb7a -[FeedMainViewController tableView:cellForRowAtIndexPath:] + 1290
27 UIKit 0x000000010a8b06b3 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 782
28 UIKit 0x000000010a8b07c8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
29 UIKit 0x000000010a886589 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2988
30 UIKit 0x000000010a8b9595 -[UITableView _performWithCachedTraitCollection:] + 92
31 UIKit 0x000000010a8a19ad -[UITableView layoutSubviews] + 218
32 UIKit 0x000000010a81211c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 710
33 QuartzCore 0x000000010918d36a -[CALayer layoutSublayers] + 146
34 QuartzCore 0x0000000109181bd0 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
35 QuartzCore 0x0000000109181a4e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
36 QuartzCore 0x00000001091761d5 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
37 QuartzCore 0x00000001091a39f0 _ZN2CA11Transaction6commitEv + 508
38 QuartzCore 0x00000001091b27cc _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 576
39 CoreFoundation 0x000000010c4de364 CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION + 20
40 CoreFoundation 0x000000010c4ddf11 __CFRunLoopDoTimer + 1089
41 CoreFoundation 0x000000010c49f8b1 __CFRunLoopRun + 1937
42 CoreFoundation 0x000000010c49ee98 CFRunLoopRunSpecific + 488
43 GraphicsServices 0x000000010da14ad2 GSEventRunModal + 161
44 UIKit 0x000000010a761676 UIApplicationMain + 171
45 App 0x00000001088a249f main + 111
46 libdyld.dylib 0x0000000110bf992d start + 1
47 ??? 0x0000000000000001 0x0 + 1
)

Can you give flexibility to show mentions by providing the indices array?

The thing is not every word starts with "@" is a valid mention. So if I get indices of all valid mentions I will be able to show only valid mentions with different color and can take care of tap on it.
I could have used NSAttributed strings easily but I am using your pod becsue it gives me taps on particular word.

Problem with Table View Cells

I have tested this and found this problem many times that inside of my table view , the cells are each another comment by users. The comments are of class "ResponsiveLabel" and sometimes the last word of a comment does not get written out. but when I put a new comment and the labels reload with the table, then some of the comments get that last word written out while a different cell will have the last word missing.

I am only using a detection of HashTags and User Handles with the label - I have also noticed that just simply using the label as a ResponiveLabel type, the labels come out as described above. Having the detection on them doesn't make any difference.

Swift 2.0: Value of type 'PatternTapResponder' (aka 'ImplicitlyUnwrappedOptional<String> -> ()') does not conform to expected dictionary value type 'AnyObject'

Hi,

I am using Swift 2.0
I have written below code.

let expansionToken = "...More"
        let tapResponderAction: PatternTapResponder = { (tappedString) -> Void in
            print("User Tapped More = " + tappedString)
            review.isExpanded = !review.isExpanded
            tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

        }

        let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: expansionToken, attributes: [NSForegroundColorAttributeName: UIColor(r: 137, g: 135, b: 135), NSFontAttributeName: UIFont(gothamRegularSize: 9), **RLTapResponderAttributeName: tapResponderAction**])

        cell.lblReview.setAttributedTruncationToken(attributedText)
        cell.lblReview.setText(reviewText, withTruncation: true)

The above bold line gives following error:
Value of type 'PatternTapResponder' (aka 'ImplicitlyUnwrappedOptional -> ()') does not conform to expected dictionary value type 'AnyObject'

And also when I write

[RLTapResponderAttributeName: tapResponderAction as! AnyObject]

into dictionary
below errors occur at runtime.

Could not cast value of type 'Swift.ImplicitlyUnwrappedOptional<Swift.String> -> ()' (0x11d334080) to 'Swift.AnyObject' (0x11be6c018)

Crashing in iPhone 5S. Says "exc_bad_access kern_invalid_address"

Here is the crash report.

[Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x1800f1bd0 objc_msgSend + 16
1  Foundation                     0x18134ee50 -[NSMutableRLEArray replaceObjectsInRange:withObject:length:] + 448
2  Foundation                     0x18134f7dc -[NSConcreteMutableAttributedString setAttributes:range:] + 100
3  Foundation                     0x18135f664 -[NSMutableAttributedString removeAttribute:range:] + 200
4  UIFoundation                   0x1856eae14 -[NSConcreteTextStorage removeAttribute:range:] + 104
5  ResponsiveLabel                0x10091bc4c __51-[ResponsiveLabel removeAttributeForTruncatedRange]_block_invoke + 240
6  CoreFoundation                 0x1809c2ed4 __65-[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:]_block_invoke + 88
7  CoreFoundation                 0x1809b0b78 -[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:] + 224
8  ResponsiveLabel                0x10091bb38 -[ResponsiveLabel removeAttributeForTruncatedRange] + 232
9  ResponsiveLabel                0x10091b984 -[ResponsiveLabel updateTextStorageReplacingRange:] + 368
10 ResponsiveLabel                0x10091ad7c -[ResponsiveLabel drawTextInRect:] + 68
11 UIKit                          0x1857ed364 -[UIView(CALayerDelegate) drawLayer:inContext:] + 368
12 QuartzCore                     0x18319d6e4 -[CALayer drawInContext:] + 260
13 QuartzCore                     0x183188784 CABackingStoreUpdate_ + 2364
14 QuartzCore                     0x1831879a4 CA::Layer::display_() + 1224
15 QuartzCore                     0x183169918 CA::Layer::display_if_needed(CA::Transaction*) + 228
16 QuartzCore                     0x183169604 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 44
17 QuartzCore                     0x183168c94 CA::Context::commit_transaction(CA::Transaction*) + 252
18 QuartzCore                     0x1831689dc CA::Transaction::commit() + 512
19 QuartzCore                     0x1831620cc CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 80
20 CoreFoundation                 0x180a28588 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
21 CoreFoundation                 0x180a2632c __CFRunLoopDoObservers + 372
22 CoreFoundation                 0x1809556a0 CFRunLoopRunSpecific + 416
23 GraphicsServices               0x181e64088 GSEventRunModal + 180
24 UIKit                          0x1857ccd90 UIApplicationMain + 204
25 Goodshows                      0x1000e4ab0 main (main.m:14)
26 libdispatch.dylib              0x1804f68b8 (Missing)](url)

Label truncation is leading to unexpected behaviour when used inside the tableview cell.

As shown in screenshot below setAttributedTruncationToken works fine (Screnshot 1) but when I tap on the cell "drawText" gets called and looks like it resizes the label again. here it is looks like. (Screenshot 2)
I don't have any idea why this is happening?
Any clue?

Other than that my text includes a newline but its seems that spacing is gone when I tap on the cell.
Check the third screenshot.
It happens only in case of newline text otherwise it works fine.

expended

truncation

screen shot 2016-01-07 at 6 59 02 pm

hightlightedTextColor = nil results in crash

It's possibe that hightlightedTextColor = nil on line 712 of responsiveLabel.m

else if (self.isHighlighted)
colour = self.highlightedTextColor;

This results (sometimes) in a crash on line 719.

Solution proposal:
else if (self.isHighlighted && self.highlightedTextColor)
colour = self.highlightedTextColor;

Change Text Color

Hi,

Thanks for library.How to change the text colour of string, for example for strings with hash tags they have some default colour

The new update crashing in iPhone 5, 5S and 5C?

Your inclusion of new category in latest commits keeps crashing on iPhone 5 family device.
any clue?

line 29 -[NSMutableAttributedString(BoundChecker) removeAttributeWithBoundsCheck:range:](exc_bad_access kern_invalid_address)
That's why what my crashanalytics showing me.

Crashed: com.apple.main-thread

0  libobjc.A.dylib                0x23d23a82 objc_msgSend + 1
1  Foundation                     0x24cb6b71 -[NSMutableRLEArray replaceObjectsInRange:withObject:length:] + 384
2  Foundation                     0x24cb730d -[NSConcreteMutableAttributedString setAttributes:range:] + 92
3  Foundation                     0x24cc55f3 -[NSMutableAttributedString removeAttribute:range:] + 182
4  UIFoundation                   0x28ac52a3 __47-[NSConcreteTextStorage removeAttribute:range:]_block_invoke + 174
5  UIFoundation                   0x28ac5119 -[NSConcreteTextStorage removeAttribute:range:] + 172
6  ResponsiveLabel                0xc69b57 -[NSMutableAttributedString(BoundChecker) removeAttributeWithBoundsCheck:range:] (NSMutableAttributedString+BoundChecker.m:29)
7  ResponsiveLabel                0xc6be2b __51-[ResponsiveLabel removeAttributeForTruncatedRange]_block_invoke (ResponsiveLabel.m:403)
8  CoreFoundation                 0x244c3cb5 __65-[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:]_block_invoke + 56
9  CoreFoundation                 0x244b49e9 -[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:] + 164
10 ResponsiveLabel                0xc6bd23 -[ResponsiveLabel removeAttributeForTruncatedRange] (ResponsiveLabel.m:405)
11 ResponsiveLabel                0xc6bb8f -[ResponsiveLabel updateTextStorageReplacingRange:] (ResponsiveLabel.m:396)
12 ResponsiveLabel                0xc6ba35 -[ResponsiveLabel appendTokenIfNeeded] (ResponsiveLabel.m:375)
13 ResponsiveLabel                0xc6b0c9 -[ResponsiveLabel drawTextInRect:] (ResponsiveLabel.m:251)
14 UIKit                          0x28bbff4d -[UILabel drawRect:] + 88
15 UIKit                          0x28bbfecb -[UIView(CALayerDelegate) drawLayer:inContext:] + 386
16 QuartzCore                     0x26bd3325 -[CALayer drawInContext:] + 228
17 QuartzCore                     0x26bbcb23 CABackingStoreUpdate_ + 1966
18 QuartzCore                     0x26cb179d ___ZN2CA5Layer8display_Ev_block_invoke + 56
19 QuartzCore                     0x26bbbfdb CA::Layer::display_() + 1322
20 QuartzCore                     0x26b9ff0d CA::Layer::display_if_needed(CA::Transaction*) + 208
21 QuartzCore                     0x26b9fbc5 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 24
22 QuartzCore                     0x26b9f081 CA::Context::commit_transaction(CA::Transaction*) + 368
23 QuartzCore                     0x26b9ed55 CA::Transaction::commit() + 520
24 QuartzCore                     0x26b984ff CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 138
25 CoreFoundation                 0x2451b2b1 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 20
26 CoreFoundation                 0x245195a7 __CFRunLoopDoObservers + 282
27 CoreFoundation                 0x245199e5 __CFRunLoopRun + 972
28 CoreFoundation                 0x244681c9 CFRunLoopRunSpecific + 516
29 CoreFoundation                 0x24467fbd CFRunLoopRunInMode + 108
30 GraphicsServices               0x25a84af9 GSEventRunModal + 160
31 UIKit                          0x28ba0435 UIApplicationMain + 144
32 Goodshows                      0xf15c1 main (main.m:14)
33 libdispatch.dylib              0x24114873 (Missing)

Zero Label view size

I have only parent ViewController(not TableViewCell) and a Label with associated ResponsiveLabel custom class.
In runtime I cannot see the label, 'cos it's zero heigh and width. Is it a feature or a bug? How can I fix this?

double hashtag

It doesn't recognize if there are 2 hashtags together...
Eg: #hastag1#hastag2

Multiple labels within a uitableview cell don't show right color

I've multiple tables within a uitableview row. But a few hashtags get highlighted, and few don't. As i scroll up and come to the cell again, it changes randomly.
Can you please check this case?

For some reason, the behavior of ResponsiveLabel in UITableView isn't consistent.

Strings that end in \r\n break truncation.

Consider the following code:

    override func viewDidLoad() {
        super.viewDidLoad()
        let expansionToken = " more..."
        let attributedTruncationText: NSMutableAttributedString = NSMutableAttributedString(string: expansionToken, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSForegroundColorAttributeName: UIColor.redColor()])
        label.setAttributedTruncationToken(attributedTruncationText)
        label.setText("Kim Young Soo and Han Gi Tak return to the land of the living, but they must get used to their new bodies.\r\n", withTruncation: true)
    }

Turning \r\n into \r\r, \n\n, or \n\r

Turns

image

Into

image

I have a sample app to reproduce if you're unable โ€” just let me know and I'll make a repo for it.

Doesn't respect numberOfLines property?

So my label.numberOfLines = 4. So it always draw a big UILabel rect even if text is just one line.
No matters how small a text is it always consider its a big as provided in numberOfLines.

Crash on - [ResponsiveLabel performActionAtIndex:] in swift 3.0

Perhaps I'm defining my closure wrong, but when defining a closure to work with a responsive label, the subsequent action execution attempts to pull a closure out of self.textStorage at memory address 0x00000

In this example, cell.containedView is a ResponsiveLabel, and hashtagResponder is an ivar defined as:

fileprivate var hashtagResponder: PatternTapResponder?
hashtagResponder = { [weak self] hashtag in
    if let strongSelf = self, let hashtag = hashtag {
        strongSelf.delegate?.didTapHashtag(name: hashtag, storySectionController: strongSelf)
    }
}
cell.containedView.enableHashTagDetection(attributes: [NSForegroundColorAttributeName : UIColor.primaryBrand, RLTapResponderAttributeName : hashtagResponder! as AnyObject])

screen shot 2017-06-12 at 1 37 23 pm

(lldb) po tapResponder
0x0000000000000000

This is not a reuse issue, because the controller that owns the PatternTapResponder is still in memory.

Any help is appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.