"调整以适应"导致UITextField类(或子类)的内存泄漏

时间:2017-03-01 10:18:47

标签: memory-leaks uitextfield subclass categories

在UITextField上使用类别时,"调整以适应"当这样的字段内的文本超出其可见边界时,最小字体大小选项可能会导致内存泄漏。我尝试了子类化,但它没有解决问题。

以下是我的类别实现的样子:

    @implementation UITextField (custom)

    static NSString *fontName = @"My-Awsome-Font";
    static UIColor *color;
    static UIFont *smallFont;
    static UIFont *largeFont;
    static NSDictionary *smallAttributes;
    static NSDictionary *largeAttributes;
    static NSString *placeholder;
    static bool shouldModifyPlaceholder;

    - (CGRect)textRectForBounds:(CGRect)bounds
    {
        if(largeFont == nil)
            largeFont = [UIFont fontWithName:fontName size:20.0];
        if(smallFont == nil)
            smallFont = [UIFont fontWithName:fontName size:16.0];
        if(smallAttributes == nil)
            smallAttributes = @{NSFontAttributeName: smallFont};
        if(largeAttributes == nil)
            largeAttributes = @{NSFontAttributeName: largeFont};

        // general elements
        [self setBackgroundColor:[UIColor whiteColor]];
        [self.layer setBorderColor:[UIColor whiteColor].CGColor];
        [self.layer setBorderWidth:2.0];

        self.font = largeFont;
        self.layer.cornerRadius = 3;
        self.clipsToBounds = YES;
        //


        shouldModifyPlaceholder = [self respondsToSelector:@selector(setAttributedPlaceholder:)] && ![placeholder isEqualToString:self.placeholder];
        // custom elements for each size category
        if (self.frame.size.width <= 90) {
            if (shouldModifyPlaceholder) {
                if ([self.placeholder length] > 3) {
                    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:smallAttributes];
                }
                else {
                    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:largeAttributes];
                }
                placeholder = self.placeholder;
            }

            return CGRectMake(bounds.origin.x + 18, bounds.origin.y + 9,
                      bounds.size.width - 36, bounds.size.height - 16);
        }
        else {
            if (shouldModifyPlaceholder) {
                self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:largeAttributes];
                placeholder = self.placeholder;
            }
            return CGRectMake(bounds.origin.x + 20, bounds.origin.y + 9,
                      bounds.size.width - 40, bounds.size.height - 16);
        }
    }

1 个答案:

答案 0 :(得分:0)

最近我发现在UITextField中输入“太多”文本会导致我的应用程序耗尽所有手机的内存并崩溃。我发现这是因为我的自定义与“调整适合”选项不兼容。删除“调整到适合”修复了问题。我还将最小字体大小属性设置为原始字体大小以确保。由于我用了一天时间试图找到解决方案,我想我会分享这个,以防其他人遇到这个问题。

change these properties