Hon*_*ney 7 iphone cocoa-touch uikit uisearchbar ios
在Cocoa-Touch中我们找到了一个控件UISearchBar.我需要自定义它,以便在文本字段中显示的搜索图标(我们单击执行相应的操作)是右对齐的.通常我们发现它保持对齐.有可能这样做吗?我做过R&D但找不到......
我该怎么做?有什么好的教程我们可以找到吗?
Ell*_*rry 18
不幸的UISearchBar是,它并非旨在直接支持这一点.在完成我们想要的工作时,我们可能不得不使用在视觉上或功能上有所妥协的解决方法,或者编写大量自定义代码.
我已经概述了几种接近我们想要和可能有用的方法.
内文UISearchBar是UITextField那就是一个子视图UISearchBar,并访问通过通常意味着即view.subviews.
放大镜搜索图标是UIImageView在leftView财产UITextField.我们可以使用以下代码将其切换到右侧:
// The text within a UISearchView is a UITextField that is a subview of that UISearchView.
UITextField *searchField;
for (UIView *subview in self.searchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
break;
}
}
// The icon is accessible through the 'leftView' property of the UITextField.
// We set it to the 'rightView' instead.
if (searchField)
{
UIView *searchIcon = searchField.leftView;
if ([searchIcon isKindOfClass:[UIImageView class]]) {
NSLog(@"aye");
}
searchField.rightView = searchIcon;
searchField.leftViewMode = UITextFieldViewModeNever;
searchField.rightViewMode = UITextFieldViewModeAlways;
}
Run Code Online (Sandbox Code Playgroud)
这给了我们以下结果:

正如您所看到的那样,图标超出了圆角矩形的边缘,并且清除图标已消失.此外,该rightView属性还用于其他内容,例如搜索结果按钮和书签按钮.将搜索图标置于此处可能会以某种方式与此功能冲突,即使您能够使用偏移量填充来正确定位它.
至少你可以使用这种方法将图标提取为a,UIImageView并将其显式定位在您认为合适的位置,就像任何其他视图一样,并编写自定义代码来处理点击事件等.
在iOS v5.0及更高版本中,您可以使用此处列出的方法自定义搜索栏的外观.以下代码使用偏移量来定位图标和文本UISearchBar:
[self.searchBar setPositionAdjustment:UIOffsetMake(255, 0) forSearchBarIcon:UISearchBarIconSearch];
[self.searchBar setSearchTextPositionAdjustment:UIOffsetMake(-270, 0)];
Run Code Online (Sandbox Code Playgroud)
在UISearchBar320宽度的标准上,它看起来像如下:

这将保持与图标相关联的所有事件功能按预期工作,但不幸的UITextField是,它被混淆,尽管它的宽度,它只显示其文本的一小部分.如果你能找到一种方法让文本显示超出它认为结束的内容UITextField,这可能是你最好的选择.
| 归档时间: |
|
| 查看次数: |
16311 次 |
| 最近记录: |