[英]How to give padding to UITextField in iOS?
我想從左邊填充填充到textfield。我已經在textfield中添加了一個背景圖像,因為textfield中的文本總是從最左邊開始。我嘗試了下面的解決方案,但這對於太多文本字段不起作用。
UIView *fieldEmail = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
self.txt_fname.leftViewMode = UITextFieldViewModeAlways;
self.txt_fname.leftView = fieldEmail;
請建議我一些簡單的解決方案,其中我不必創建一個單獨的視圖來給出填充。
問題中接受的答案對我不起作用。 使用UITextBorderStyleNone為UITextField設置填充
您可以像下面的代碼一樣創建UITextFiled的類別:
.H班
#import <UIKit/UIKit.h>
@interface UITextField (Textpadding)
-(CGRect)textRectForBounds:(CGRect)bounds;
-(CGRect)editingRectForBounds:(CGRect)bounds;
@end
.M班
#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];
}
此類別將在運行時默認設置所有文本字段填充。
如何創建類別
現在就是這個類中的代碼作為我的答案。
另一個更簡單,更快捷的解決方案是,您可以創建一個imageview並為其添加textfield圖像。 然后在imageview頂部添加真實文本字段,並根據需要移動它,例如,當你想要左邊填充時,你可以將文本字段從imageview的x-cordinate移開一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.