I want to replace a substring (e.g. @\"replace\"
) of an NSAttributedString
with another NSAttributedString
.
I am looking for a
I have a specific requirement and fixed like below. This might help someone.
Requirement: In the storyboard, rich text directly added to UITextView's attribute which contains a word "App Version: 1.0". Now I have to dynamise the version number by reading it from info plist.
Solution: Deleted version number 1.0 from the storyboard, just kept "App Version:" and added below code.
NSAttributedString *attribute = self.firsttextView.attributedText;
NSMutableAttributedString *mutableAttri = [[NSMutableAttributedString alloc] initWithAttributedString:attribute];
NSString *appVersionText = @"App Version:";
if ([[mutableAttri mutableString] containsString:appVersionText]) {
NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
NSString* version = [infoDict objectForKey:@"CFBundleShortVersionString"];
NSString *newappversion = [NSString stringWithFormat:@"%@ %@",appVersionText,version] ;
[[mutableAttri mutableString] replaceOccurrencesOfString:appVersionText withString:newappversion options:NSCaseInsensitiveSearch range:NSMakeRange(0, mutableAttri.length)];
self.firsttextView.attributedText = mutableAttri;
}
Done!! Updated/modified attributedText.