UITextView style is being reset after setting text

2019-01-08 05:05发布

问题:

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"];
}

回答1:

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.



回答2:

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


回答3:

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



回答4:

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];
    }
}


回答5:

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.



回答6:

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
        }
    }
}


回答7:

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.



回答8:

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.



回答9:

This worked for me:

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


回答10:

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.



回答11:

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.



回答12:

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


回答13:

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
    }
}