UITextView style is being reset after setting text property

IosCocoa TouchFontsUitextview

Ios Problem Overview


I have UITextView *_masterText and after call method setText property font is being reset. It's happening after I change sdk 7. _masterText is IBOutlet, global and properties are set in storyboard. It's only me or this is general SDK bug?

@interface myViewController : UIViewController
{
  IBOutlet UITextView *_masterText;
}

@implementation myViewController

-(void)viewWillAppear:(BOOL)animated
{
    [_masterText setText:@"New text"];
}

Ios Solutions


Solution 1 - Ios

Sitting with this for hours, I found the bug. If the property "Selectable" = NO it will reset the font and fontcolor when setText is used.

So turn Selectable ON and the bug is gone.

Solution 2 - Ios

I ran into the same issue (on Xcode 6.1) and while John Cogan's answer worked for me, I found that extending the UITextView class with a category was a better solution for my particular project.

interface
@interface UITextView (XcodeSetTextFormattingBugWorkaround)
    - (void)setSafeText:(NSString *)textValue;
@end
implementation
@implementation UITextView (XcodeSetTextFormattingBugWorkaround)
- (void)setSafeText:(NSString *)textValue
{
    BOOL selectable = [self isSelectable];
    [self setSelectable:YES];
    [self setText:textValue];
    [self setSelectable:selectable];
}
@end

Solution 3 - Ios

If you want your text view to be "read only" you can check Editable and Selectable and uncheck User Interaction Enabled, with this the UITextView was behaving as I wanted

enter image description here

enter image description here

Solution 4 - Ios

Had this issue myself and the above answer helped but I added a wrapper to my ViewController code as follows and just pass the uiview instance and text to change and the wrapper function toggles the Selectable value on, changes text and then turns it off again. Helpful when you need the uitextview to be off at all times by default.

/*
    We set the text views Selectable value to YES temporarily, change text and turn it off again.
    This is a known bug that if the selectable value = NO the view loses its formatting.
 */
-(void)changeTextOfUiTextViewAndKeepFormatting:(UITextView*)viewToUpdate withText:(NSString*)textValue
{
    if(![viewToUpdate isSelectable]){
        [viewToUpdate setSelectable:YES];
        [viewToUpdate setText:textValue];
        [viewToUpdate setSelectable:NO];
    }else{
        [viewToUpdate setText:textValue];
        [viewToUpdate setSelectable:NO];
    }
}

Solution 5 - Ios

EDIT :

Setting font for UITextView in iOS 7 work for me if firstly you set the text and after that you set the font :

@property (nonatomic, weak) IBOutlet UITextView *masterText;

@implementation myViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    _myTextView.text = @"My Text";

    _myTextView.font = [UIFont fontWithName:@"Helvetica.ttf" size:16]; // Set Font
    
}

On a XIB file, if you add some text in your UITextView and change the font or the color it will work.

Solution 6 - Ios

Here's a quick subclass solution I often use for this problem.

class WorkaroundTextView: UITextView {
    override var text: String! {
        get {
            return super.text
        }
        set {
            let originalSelectableValue = self.selectable
            self.selectable = true
            super.text = newValue
            self.selectable = originalSelectableValue
        }
    }
}

Solution 7 - Ios

This issue resurfaced in Xcode 8. This is how I fixed it:

Changed the extension to:

extension UITextView{
    func setTextAvoidXcodeIssue(newText : String, selectable: Bool){
        isSelectable = true
        text = newText
        isSelectable = selectable
    }
}

and checked the Selectable option in the Interface Builder.

It's not very elegant to have that 'selectable' parameter but it'll do.

Solution 8 - Ios

In iOS 8.3, the workaround of setting "selectable" to YES before the setText, and NO after, didn't fix it for me.

I found I needed to set "selectable" to YES in the storyboard, too, before this would work.

Solution 9 - Ios

This worked for me:

let font = textView.font
textView.attributedText = attributedString
textView.font  = font

Solution 10 - Ios

I am having this problem to. A swifty-friendly solution of @Ken Steele's answer answer. I extend the UITextView and add a computed property.

extension UITextView {
    // For older Swift version output should be NSString!
    public var safeText:String!
        {
        set {
            let selectable = self.selectable;
            self.selectable = true;
            self.text = newValue;
            self.selectable = selectable;
        }
        get {
            return self.text;
        }
    }
}

hope it helps.

Solution 11 - Ios

For me with attributed text, I just needed to set the font in the attributes dictionary rather than setting it in it's own field.

Solution 12 - Ios

Its been 3 years and the bug still exists in the latest stable version of Xcode (7.3). Clearly apple wont be fixing it any time soon leaving developers with two options: leaving selectable on and setting UserInteractionEnabled to false or Method swizzling.

If you have a button on your textView the former will not suffice.

No-code-change-requied solution in swift:

import UIKit

extension UITextView {
    @nonobjc var text: String! {
        get {
            return performSelector(Selector("text")).takeUnretainedValue() as? String ?? ""
        } set {
            let originalSelectableValue = selectable
            selectable = true
            performSelector(Selector("setText:"), withObject: newValue)
            selectable = originalSelectableValue
        }
    }
}

Objective-C:

#import <objc/runtime.h>
#import <UIKit/UIKit.h>

@implementation UITextView (SetTextFix)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
    
        SEL originalSelector = @selector(setText:);
        SEL swizzledSelector = @selector(xxx_setText:);
    
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
        BOOL didAddMethod =
        class_addMethod(class,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));
    
        if (didAddMethod) {
            class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
       }
   });
}

- (void)xxx_setText:(NSString *)text {
    BOOL originalSelectableValue = self.selectable;
    self.selectable = YES;
    [self xxx_setText:text];
    self.selectable = originalSelectableValue;
}

@end

Solution 13 - Ios

Using the work-around discussed in this issue, this extension to UITextView provides a setTextInCurrentStyle() function. Based on solution by Alessandro Ranaldi but does not require the current isSelectable value to be passed to the function.

extension UITextView{
    func setTextInCurrentStyle(_ newText: String) {
        let selectablePreviously = self.isSelectable
        isSelectable = true
        text = newText
        isSelectable = selectablePreviously
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBłażejView Question on Stackoverflow
Solution 1 - IosBosse NilssonView Answer on Stackoverflow
Solution 2 - IosKen SteeleView Answer on Stackoverflow
Solution 3 - IosChuy47View Answer on Stackoverflow
Solution 4 - IosJohn CoganView Answer on Stackoverflow
Solution 5 - IosJordan MontelView Answer on Stackoverflow
Solution 6 - IosWaltersGE1View Answer on Stackoverflow
Solution 7 - IosAlessandro RanaldiView Answer on Stackoverflow
Solution 8 - IosPeter JohnsonView Answer on Stackoverflow
Solution 9 - IosDavid GreenView Answer on Stackoverflow
Solution 10 - IosLastMoveView Answer on Stackoverflow
Solution 11 - IosloudmouthView Answer on Stackoverflow
Solution 12 - IosMark BourkeView Answer on Stackoverflow
Solution 13 - IosDuncan BabbageView Answer on Stackoverflow