UITextView设置文本属性后,样式被重置

146

我有一个UITextView *_masterText,在调用方法setText后,字体属性会被重置。这是发生在我更新SDK 7之后的情况。_masterText是一个IBOutlet,是全局的,在storyboard中设置了属性。这是只有我遇到的问题还是普遍存在的SDK bug?

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

@implementation myViewController

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

0

使用讨论中提到的解决方案,这个对UITextView的扩展提供了一个setTextInCurrentStyle()函数。这个解决方案是基于Alessandro Ranaldi的方案,但不需要将当前的isSelectable值传递给该函数。

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

0

已经过去了3年,最新稳定版本Xcode(7.3)中仍然存在该错误。显然,苹果不会很快修复它,这让开发人员面临两个选择:将可选择性保留并将UserInteractionEnabled设置为false或使用方法交换。

如果您的textView上有一个按钮,则前者无法满足要求。

在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

0
对于带属性文本,我只需要在属性字典中设置字体,而不是在其自己的字段中设置字体。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接