Replace substring of NSAttributedString with another NSAttributedString

前端 未结 9 1120
野趣味
野趣味 2020-12-01 08:51

I want to replace a substring (e.g. @\"replace\") of an NSAttributedString with another NSAttributedString.

I am looking for a

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 09:33

    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.

提交回复
热议问题