UITextField的文本插入?

泄露秘密 提交于 2020-02-26 00:10:03

我想插入一个UITextField文本

这可能吗?


#1楼

使用textRectForBounds:是正确的方法。 我将其包装在子类中,因此您可以简单地使用textEdgeInsets 。 参见SSTextField


#2楼

我能够通过以下方式做到这一点:

myTextField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0);

当然,请记住导入QuartzCore并将框架添加到您的项目中。


#3楼

如果只需要左边距,则可以尝试以下操作:

UItextField *textField = [[UITextField alloc] initWithFrame:...];
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, textField.frame.size.height)];
leftView.backgroundColor = textField.backgroundColor;
textField.leftView = leftView;
textField.leftViewMode = UITextFieldViewModeAlways;

这个对我有用。 希望对您有所帮助。


#4楼

如果只想更改TOP和LEFT缩进,则

//占位符位置

- (CGRect)textRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );
}

//文字位置

- (CGRect)editingRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );
}

#5楼

向UITextField添加填充的一种好方法是子类化UITextField并添加edgeInsets属性。 然后,您设置edgeInsets,并将相应绘制UITextField。 使用自定义的leftView或rightView集也可以正常运行。

OSTextField.h

#import <UIKit/UIKit.h>

@interface OSTextField : UITextField

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end

OSTextField.m

#import "OSTextField.h"

@implementation OSTextField

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

- (CGRect)textRectForBounds:(CGRect)bounds {
    return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

@end
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!