如何在iOS中为UITextField提供填充? [英] How to give padding to UITextField in iOS?

查看:196
本文介绍了如何在iOS中为UITextField提供填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从左侧填充填充到textfield。我已经在textfield中添加了一个背景图像,因为textfield中的文本总是从最左边开始。我尝试过以下解决方案,但这对于太多文本字段不起作用。

I want to give padding from left into the textfield.I have added a background image to textfield due to which text in textfield always start from very left edge.I have tried below solution but that does not work for too many text fields.

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

请给我一些简单的解决方案,其中我不需要创建一个单独的视图来给出填充。

Please suggest me some simple solutin in which i don't have to create a seprate view for giving the padding.

问题中接受的答案对我不起作用。
使用UITextBorderStyleNone设置UITextField的填充

The answer accepted in the question does not work for me. Set padding for UITextField with UITextBorderStyleNone

推荐答案

您可以创建一个UITextFiled类别,如下面的代码:

You can create a Category of UITextFiled like following code:

.H class

#import <UIKit/UIKit.h>

@interface UITextField (Textpadding)


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

.M class

#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];
}

此类别将在运行时默认设置所有文本字段填充。

This category will setting your all text-filed padding by default at run time.

如何创建类别


  • 按cmd + n用于新类创建并选择Objective-c类。


  • 然后选择类别如下。


  • 设置班级名称。


  • 设置文件姓名。

这就是我现在在这个课程中的代码作为我的答案。

That's it now do code in this class as my answer.

这篇关于如何在iOS中为UITextField提供填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆