![](/img/trans.png)
[英]UITextField Alignment : Placeholder right aligned & Actual text gets left aligned
[英]How to create UITextField with placeholder to the left and edited text to the right?
如何使用左側占位符和右側編輯文本創建UITextField?
UITextField本身不允許使用其屬性將占位符和編輯的文本放到不同的方面。 嘗試在故事板中設置它 - >屬性檢查器 - >對齊。 它們都在左邊或右邊。 僅對占位符或僅對文本沒有特殊對齊。
為此,您應該將UILabel
添加到UITextField
,該UILabel
不可編輯且不允許觸摸。 然后將UITextField
上的文本對齊方式設置為NSTextAlignmentRight
。
首先,將文本對齊方式設置為右側:
[textField setTextAlignment:NSTextAlignmentRight];
leftView
占位符,可以將其添加為子視圖,或使用leftView
屬性:
[textField setLeftView:<your label here>];
我剛剛創建了一個自定義的UITextField子類來執行此操作。 要使用它,只需在Storyboard或Xib上創建UITextField ...在其中放置占位符文本,將文本字段類設置為OBSTextFieldWithLabel,然后您可以使用以下代碼:
@interface OBSTextFieldWithLabel : UITextField
@end
@implementation OBSTextFieldWithLabel
- (void)awakeFromNib
{
[super awakeFromNib];
NSString *labelText = [self placeholder];
self.placeholder = nil;
CGRect labelFrame = CGRectMake(20, 10, 150, 15);
UILabel *placeholderLabel = [[UILabel alloc] initWithFrame:labelFrame];
[placeholderLabel setFont:[UIFont systemFontOfSize:12]];
[placeholderLabel setTextColor:[UIColor lightGrayColor]];
[placeholderLabel setText:labelText];
[self addSubview:placeholderLabel];
[self setTextAlignment:NSTextAlignmentRight];
}
@end
這可能不是100%完美,因為標簽大小沒有動態設置和所有...但它應該讓你啟動並運行它的工作原理:-)
我寫了一個可以幫助你的控件。 本質上它是用於在編輯時突出顯示UITextField,但它也有一個左側占位符的機制,如屏幕截圖所示。
https://www.cocoacontrols.com/controls/sahighlightedtextfield
希望這能指出你正確的方向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.