我尝试在IOS 7中继承UISearchBar
,以便占位符始终保持对齐。
我这样做了:
- (void)layoutSubviews {
[super layoutSubviews];
UITextField * tv = self.textField;
tv.textAlignment = NSTextAlignmentLeft ;
}
如果tv.textAlignment = NSTextAlignmentRight
,那么我设法将文字设为右侧。
但是,UISearchBar
为空且显示占位符时的文字始终显示在中心。
我想知道为什么。我把它放在layoutSubviews
方法中。因此,每次绘制控件时都应绘制它。
答案 0 :(得分:1)
您可以使用UIAppearance
尝试此操作。
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextAlignment:NSTextAlignmentLeft];
Downvoters,请阅读:note from Apple:
注意:当视图进入窗口时,iOS会应用外观更改,但它不会更改已在窗口中的视图的外观。要更改当前在窗口中的视图的外观,请从视图层次结构中删除该视图,然后将其放回。
答案 1 :(得分:0)
我在几天前遇到同样的问题,但是没有办法改变搜索栏的占位符文本的对齐方式,我测试了很多“SO”答案,但没有人工作。 最后我决定跟随修复。
在占位符文字的左/右(如你所愿)中添加一些空格
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 6.1) {
// Load resources for iOS 6.1 or earlier
self.searchBar.placeholder = @"hello";
}
else
{
// Load resources for iOS 7 or later
// Add some white space in Left/right *(as you want)* here i added to left
self.searchBar.placeholder = @" hello";
}
答案 2 :(得分:0)
通过NSLog searchBar的textField子视图,可以得到这样的结果:
<_UISearchBarSearchFieldBackgroundView: 0x8d492e0; frame = (0 0; 304 28); opaque = NO; autoresize = W+H; userInteractionEnabled = NO; layer = <CALayer: 0x8d49410>> - (null),
<UIImageView: 0x8d488a0; frame = (102.5 7.5; 12.5 12.5); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x8d48f80>> - (null),
<UISearchBarTextFieldLabel: 0x8d4b410; frame = (122.5 1; 181.5 25); text = 'hello000000'; clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x8d4b520>>
)
你可以看到,UISearchBarTextFieldLabel
是显示占位符的UI,这里是'hello000000',它是UILabel的子类。因此,设置searchBar的textField textAlignment不会直接影响占位符位置。占位符标签的布局由searchBar的textField - (void)layoutSubviews
处理,而你不能覆盖内部textField这个方法。
基于UIView的自定义searchBar,添加覆盖- (void)layoutSubviews
的UITextField的子类,甚至添加添加UILabel,其中textfield的文本为空,删除时不删除。也许是一个解决方案。
添加一些我的测试代码:
@interface CustomSearchBar : UIView {
}
@end
@implementation SharedSearchBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_textField = [[SearchTextField alloc] initWithFrame:CGRectMake(10, 6, frame.size.width-20, frame.size.height-12)];
_textField.leftView = UIImageViewNamed(@"search_glass");
[self addSubview:_textField];
}
return self;
}
@end
@interface SearchTextField : UITextField
@end
@implementation SearchTextField
- (void)layoutSubviews{
[super layoutSubviews];
for (UIView *subView in self.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
UILabel *lb = (UILabel *)subView;
lb.textAlignment = UITextAlignmentRight;
lb.text = @"123123";
CGRect frame = lb.frame;
frame.origin.x = textFiled.frame.size.width-frame.size.width;
lb.frame = frame;
break;
}
}
}
@end