如何在 iOS 中为 UITextField 提供填充?

How to give padding to UITextField in iOS?

我想从左边填充到 textfield.I 已将背景图像添加到文本字段,因为文本字段中的文本总是从最左边开始 edge.I 已尝试以下解决方案,但没有适用于过多的文本字段。

    UIView *fieldEmail = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    self.txt_fname.leftViewMode = UITextFieldViewModeAlways;
    self.txt_fname.leftView     = fieldEmail;

请给我一些简单的解决方案,我不必在其中创建单独的视图来提供填充。

问题中接受的答案对我不起作用。 Set padding for UITextField with UITextBorderStyleNone

您可以像下面的代码一样创建 UITextFiled 的类别:

.Hclass

#import <UIKit/UIKit.h>

@interface UITextField (Textpadding)


-(CGRect)textRectForBounds:(CGRect)bounds;
-(CGRect)editingRectForBounds:(CGRect)bounds;
@end

.Mclass

#import "UITextField+Textpadding.h"

@implementation UITextField (Textpadding)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
-(CGRect)textRectForBounds:(CGRect)bounds {



    return CGRectMake(bounds.origin.x+20 , bounds.origin.y ,
                      bounds.size.width , bounds.size.height-2 );
}
-(CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}

默认情况下,此类别将在 运行 时设置所有文本文件的填充。

如何创建类别

  • 按 cmd+n 新建 class 创建和 select Objective-c class.

  • 然后select分类如下。

  • 设置Class名称。

  • 设置文件名。

就是这样,现在在这个 class 中编写代码作为我的答案。

另一个更简单快捷的解决方案是制作图像视图并在其中为文本字段添加图像。然后在 imageview 的顶部添加真正的文本字段,并根据需要移动它,例如,当你想要左填充时,你可以将文本字段移动到离 imageview 的 x 坐标稍远的地方。