2012-07-09 110 views
5

我将需要显示的UISearchBar,因为不同的输入语言的不同路线。
只见this answer,但我找不到它在哪里,你实际上对齐文本,以利对UISearchBar是否可以更改UISearchBar占位符的对齐方式?

任何想法?
谢谢!

+0

对于斯威夫特3. 我发现这里的解决方案:* *轻松自定义文本框**](http://stackoverflow.com/a/40105165/4593553) – Jerome 2016-10-18 10:13:01

回答

6

这是我做了什么:

for (UIView *subView in self.subviews){ 
     if ([subView isKindOfClass:[UITextField class]]) { 
      UITextField *text = (UITextField*)subView; 
      text.textAlignment = UITextAlignmentRight; 
      text.rightViewMode = UITextFieldViewModeAlways; 
     } 
    } 

如果你也想移动的放大镜图标,你可以这样做:

text.leftView = nil; 
text.rightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search_icon.png"]]; 

但你必须提供search_icon .png图片。

+0

顺便说一下,让这个与iOS 7工作,你需要: [self.subviews objectAtIndex:0]子视图]中for循环而不只是self.subviews – 2014-04-09 17:15:03

3

下面是解

UITextField *searchTextField = [searchBar valueForKey:@"_searchField"]; 
UILabel *placeholderLabel = [searchTextField valueForKey:@"_placeholderLabel"]; 
[placeholderLabel setTextAlignment:NSTextAlignmentLeft]; 
+0

我得到“预期]”的错误,第二行 – SleepsOnNewspapers 2015-04-28 16:36:54

+1

存在丢失的冒号,请把谓。 – 2015-04-28 16:51:06

+1

更新了答案! – 2015-04-28 16:52:40

0

集归因占位符文本,实现靠左对齐占位符,试试这个代码...

//Step1 : Make blank attributed string 
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:@""]; 

    //Step2 : Append placeholder to blank attributed string 
    NSString *strSearchHere = @"Search here..."; 
    NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName]; 
    NSAttributedString * subString = [[NSAttributedString alloc] initWithString:strSearchHere attributes:attributes]; 
    [attributedString appendAttributedString:subString]; 

    //Step3 : Append dummy text to blank attributed string 
    NSString *strLongText = @"LongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongTextLongText"; 
    NSDictionary * attributesLong = [NSDictionary dictionaryWithObject:[UIColor clearColor] forKey:NSForegroundColorAttributeName]; 
    NSAttributedString * subStringLong = [[NSAttributedString alloc] initWithString:strLongText attributes:attributesLong]; 
    [attributedString appendAttributedString:subStringLong]; 

    //Step4 : Set attributed placeholder string to searchBar textfield 
    UITextField *searchTextField = [searchBarr valueForKey:@"_searchField"]; 
    searchTextField.attributedPlaceholder = attributedString; 
    searchTextField.leftView = nil; //To Remove Search icon 
    searchTextField.textAlignment = NSTextAlignmentLeft; 
相关问题