是可以改变一个UISearchBar占位符的alignment?
由于不同的input语言,我将需要以不同的alignment方式显示UISearchBar。
我看到了这个答案 ,但我无法find你在UISearchBar
上实际alignment文本的位置。
有任何想法吗?
谢谢!
这就是我所做的:
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图片。
这是解决scheme
UITextField *searchTextField = [searchBar valueForKey:@"_searchField"]; UILabel *placeholderLabel = [searchTextField valueForKey:@"_placeholderLabel"]; [placeholderLabel setTextAlignment:NSTextAlignmentLeft];
设置属性的占位符文本来实现左alignment的占位符,试试这个代码…
//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;