2011-07-22 71 views

回答

12

的UITextField做法是不工作了,可能是由于物体的UISearchBar的改型。 UISearchBar在其显示在屏幕上时调整其UITextField的大小,这会使UITextField上的所有操作无效。

不过,我发现的UISearchBar响应setContentInset:方法(在iOS 5.0.1测试)。它调整封闭视图的插入距离。

该结果在涉及NSInvocation的一个复杂的方法:在使用的CGRect

if([aSearchBar respondsToSelector:@selector(setContentInset:)]) 
{ 
    SEL aSelector = NSSelectorFromString(@"setContentInset:"); 
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[aSearchBar methodSignatureForSelector:aSelector]]; 

    [inv setSelector:aSelector]; 
    [inv setTarget:aSearchBar]; 
    UIEdgeInsets anInsets = UIEdgeInsetsMake(5, 0, 5, 35); 
    [inv setArgument:&anInsets atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation 
    [inv invoke]; 
} 

上面的代码大小调整的UISearchBar(有效的UITextField)的contentInsetanInsets参数指示。父级if语句(respondsToSelector:)可以避免在iOS新版本中发生此行为更改。

更新了Swift3和iOS10:

if searchBar.responds(to: Selector("setContentInset:")) { 
    let aSelector = Selector("setContentInset:") 
    let anInset = UIEdgeInsetsMake(5, 0, 5, 35) 
    searchBar.perform(aSelector, with: anInset) 
} 
+1

工程就像一个魅力。例如,要留下一定的空间和权利,使用上面: 'UIEdgeInsets anInsets = UIEdgeInsetsMake(5,50/*左*/5,50/*权* /);' – ecotax

+0

我发现,如果你离开顶部和底部的插图为0,它应用默认插入。设置为5,但当我选择导致它移动到搜索栏顶部的文本字段时发生。 – Jonah

+0

此代码是否会从AppStore中拒绝您的应用程序?除此之外,它的确,工作就像一个魅力 –