在iOS 7中,UISearchbar占位符居中对齐并覆盖书签按钮,直到未选择搜索栏:
选择后,它看起来像预期的那样:
我一直需要它看起来像这样。谢谢你。
最佳答案
新解决方案:
//
// WPViewController.m
// test
//
// Created by VASANTH K on 02/01/14.
//
//
#import "WPViewController.h"
@interface WPViewController ()
{
UILabel *lableCopy;
}
@end
@implementation WPViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//[self fixSearchBar:searchBar];
// Do any additional setup after loading the view, typically from a nib.
self.searchBar.delegate=self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.searchBar resignFirstResponder];
//[self fixSearchBar:searchBar];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self fixSearchBar:self.searchBar];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)search
{
[self fixSearchBar:self.searchBar];
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[self fixSearchBar:self.searchBar];
}
-(void)fixSearchBar:(UISearchBar*)searchBar
{
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
// [searchField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];
UILabel *lable=[searchField valueForKey:@"_placeholderLabel"];
if(!lableCopy)
{
lableCopy=[[UILabel alloc]initWithFrame:lable.frame];
lableCopy.font=lable.font;
[lableCopy setText:lable.text];
[lableCopy setTextColor:lable.textColor];
UIButton *button;
for (UIView *view in [[[[searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:1] subviews]) {
if([view isKindOfClass:[UIButton class]])
{
button=(UIButton*)view;
break;
}
}
if(button)
{
//lable.hidden=YES;
CGRect newFrame=lable.frame;
newFrame.size.width=button.frame.origin.x-lable.frame.origin.x;
lableCopy.frame=newFrame;
[lableCopy adjustsFontSizeToFitWidth];
//lableCopy.backgroundColor=[UIColor blackColor];
[searchField addSubview:lableCopy];
lableCopy.text=lable.text;
//lableCopy.textColor=[UIColor redColor];
}
}
for (UIView *view in [[searchBar.subviews objectAtIndex:0] subviews]) {
if([view isKindOfClass:[UITextField class]])
{
// NSLog(@"%@",view);
NSLog(@"TextFieldPresent==>%@",view);
if([view isFirstResponder])
{
lable.hidden=NO;
lableCopy.hidden=YES;
}
else
{
lable.hidden=YES;
lableCopy.hidden=NO;
}
break;
}
}
}
@end
该解决方案只是添加了新的UILable View 并隐藏了现有的占位符,以使您真正拥有searchBar的感觉。
这可能是修复IOS7中该UI问题的临时技巧。
旧解决方案:
[searchField setValue:[NSNumber numberWithBool:YES] for KeyPath:@“_ placeholderLabel.adjustsFontSizeToFitWidth”];
在ios7中将无法使用,因为用于显示内容的标签的大小足以显示文本,问题在于ios7的标签宽度错误。无法调整标签宽度的大小。
几乎没有办法解决此问题。
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
UILabel *lable=[searchBar valueForKey:@"_placeholderLabel"];
lable.font=[UIFont fontWithName:lable.font.fontName size:10.0];
根据您自己的搜索栏宽度计算字体大小。我也尝试更改特定标签的宽度,但是它永远无法正常工作。
关于iphone - iOS 7中的UISearchBar占位符对齐和裁剪,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19257544/