UITextField 编辑时问题整理

2019-04-13  本文已影响0人  zhu哥哥

1、自动撑满宽度

        _textField.adjustsFontSizeToFitWidth = YES;
        _textField.minimumFontSize = 20;

2、编辑时向左偏移

1、UITextField 一共有如下几个View 组成:UIFieldEditor、UITextFieldContentView、UITextFieldRoundedRectBackgroundViewNeue、UITextField,对应的frame 分别为:
<UIFieldEditor; frame = (7 2; 146 26);
<_UITextFieldContentView; frame = (0 -3.5; 150 35.5);
<_UITextFieldRoundedRectBackgroundViewNeue; frame = (0 0; 160 30);
<UITextField; frame = (123.5 89.5; 160 30);
2、编辑时 是在 UIFieldEditor,继承自UIScrollView,修改contentOffset 即可搞定 向左向下的偏移
3、重新 layoutSubviews

- (void)layoutSubviews {
    [super layoutSubviews];
    for (UIScrollView *fieldEditor in self.textField.subviews) {
        if ([fieldEditor isKindOfClass:[UIScrollView class]]) { // UIFieldEditor
            CGFloat currentXOffset = 0.0f;
            for (UIView *fieldEditorContentView in fieldEditor.subviews) { //_FieldEditorContentView
                currentXOffset = fieldEditorContentView.frame.origin.x;
                if (_defaultXOffset == 0.0f && currentXOffset != 0.0f) {
                    _defaultXOffset = currentXOffset;
                }
            }
            CGPoint offset = fieldEditor.contentOffset;
            if (currentXOffset == 0.0f && _defaultXOffset != 0.0f) {
                offset.x = -_defaultXOffset;
            } else {
                offset.x = 0.0f;
            }
            if (self.textField.text.length == 0) { //字体为空时重置_defaultXOffset
                offset.x = 0.0f;
                _defaultXOffset = 0.0f;
            }
            fieldEditor.contentOffset = offset;
            break;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读