简体   繁体   English

如何在 UISearchBar 中更改 UITextField position?

[英]How can I change a UITextField position in UISearchBar?

Is there a way to reposition UITextField inside UISearchBar?有没有办法在 UISearchBar 中重新定位 UITextField ? I'd like to move UITextField inside UISearchBar up a little bit.我想将 UISearchBar 内的 UITextField 向上移动一点。

The UITextField approach is not working anymore, probably due to a restyling of the UISearchBar object. UITextField 方法不再起作用,可能是由于 UISearchBar object 的重新设置。 UISearchBar resizes its UITextField when it is presented on screen, this invalidates all manipulations on the UITextField. UISearchBar 在屏幕上显示其 UITextField 时会调整其大小,这会使 UITextField 上的所有操作无效。

However, I discovered that UISearchBar responds to the setContentInset: method (tested on iOS 5.0.1).但是,我发现 UISearchBar 响应setContentInset:方法(在 iOS 5.0.1 上测试)。 It adjusts the inset distance from the enclosing view.它调整与封闭视图的插入距离。

This result in a sophisticated approach involving NSInvocation:这导致了一种涉及 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];
}

The above code resizes the contentInset of the UISearchBar (effectively UITextField) using the CGRect indicated in the anInsets parameter.上面的代码使用anInsets参数中指示的contentInset调整 UISearchBar 的 contentInset(实际上是 UITextField)的大小。 The parent if-statement ( respondsToSelector: ) saves yourself from changes of this behaviour in new versions of iOS.父 if 语句 ( respondsToSelector: :) 在 iOS 的新版本中避免了这种行为的变化。

Updated for Swift3 and iOS10:针对 Swift3 和 iOS10 更新:

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

Swift 4+ Swift 4+

You can try this.你可以试试这个。

searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

It doesn't move the textField, but moves the text.它不会移动文本字段,而是移动文本。 This should be enough for most people.这对大多数人来说应该足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM