如何更改UISearchBar中的UITextField位置? [英] How can I change a UITextField position in UISearchBar?

查看:94
本文介绍了如何更改UISearchBar中的UITextField位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在UISearchBar中重新定位UITextField? 我想将UISearchBar内的UITextField向上移动一点.

Is there a way to reposition UITextField inside UISearchBar? I'd like to move UITextField inside UISearchBar up a little bit.

推荐答案

UITextField方法不再起作用,可能是由于UISearchBar对象的样式改变了. UISearchBar在屏幕上显示时会调整其UITextField的大小,这会使UITextField上的所有操作失效.

The UITextField approach is not working anymore, probably due to a restyling of the UISearchBar object. UISearchBar resizes its UITextField when it is presented on screen, this invalidates all manipulations on the UITextField.

但是,我发现UISearchBar响应setContentInset:方法(在iOS 5.0.1上测试).可以从封闭视图调整插入距离.

However, I discovered that UISearchBar responds to the setContentInset: method (tested on iOS 5.0.1). It adjusts the inset distance from the enclosing view.

这导致涉及NSInvocation的复杂方法:

This result in a sophisticated approach involving NSInvocation:

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];
}

上面的代码使用anInsets参数中指示的CGRect调整了UISearchBar(有效地是UITextField)的contentInset的大小.父if语句(respondsToSelector:)使您避免在新版本的iOS中更改此行为.

The above code resizes the contentInset of the UISearchBar (effectively UITextField) using the CGRect indicated in the anInsets parameter. The parent if-statement (respondsToSelector:) saves yourself from changes of this behaviour in new versions of 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)
}

这篇关于如何更改UISearchBar中的UITextField位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆