I am trying to subclass NSMutableAttributedString
, but I have found I am incapable of using it in any shape or form. Even as a freshly created subclass, it cannot be initialized:
The exception I receive is as follows:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ALCTMutableAttributedString initWithString:]: unrecognized selector sent to instance 0x16d21680'
It won't even work with a bare initialization call:
ALCTMutableAttributedString *newString = [[ALCTMutableAttributedString alloc]init];
And here is the bare contents of the Subclass:
Header File:
#import <Foundation/Foundation.h>
@interface ALCTMutableAttributedString : NSMutableAttributedString
@end
Implementation File:
#import "ALCTMutableAttributedString.h"
@implementation ALCTMutableAttributedString
@end
I'm pretty perplexed as to why this is disallowed, or not possible within my project. Might anyone know why?
Extension:
To demonstrate how I'm using the class, here is the header of the class in which I use it:
#import <UIKit/UIKit.h>
#import "Foundation/Foundation.h"
#import "CXCommentLabel.h"
#import "ALCTMutableAttributedString.h"
@interface CXPodcastViewController : UIViewController
@property (nonatomic,weak)IBOutlet CXCommentLabel *commentLabel;
@property (nonatomic,weak)IBOutlet NSLayoutConstraint *commentLabelHeightConstraint;
@property (nonatomic,weak)IBOutlet UIButton *resizeButton;
-(IBAction)resizeTheLabel:(id)sender;
@end
Here is how I call it: (.m file)
-(void)resizeTheLabel:(id)sender {
// Crash here
ALCTMutableAttributedString *newString = [[ALCTMutableAttributedString alloc]init];
// Crash here ^
[self.commentLabel setAttributedText:newString];
}
Check this Apple document ", In the apple documentation itself there s a section called "Alternatives to Subclassing" please check that too"
Subclassing of string using NSMutableAttributedString is not possible.
Alternative way to use the nsmutableattributed string is
-(void)resizeTheLabel:(id)sender {
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:@"string" attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
[self.commentLabel setAttributedText:newString];
}
Add the desired attribute to the dictionary and pass it as a parameter. Happy Coding :)