3

你能告诉我如何在 iOS 7 中右对齐 UISearchbar 文本吗?,我在 iOS6 中使用它,但现在它在 iOS7 中不起作用:

//hacking search bar
UITextField *searchField;
for (UIView *subview in self.searchBar.subviews)
{

       if ([subview isKindOfClass:[UITextField class]]) {
        searchField = (UITextField *)subview;
        break;
    }
}
if (searchField) {
    searchField.textAlignment = NSTextAlignmentRight;
}
4

6 回答 6

1

不幸的是,如果不从头开始完全重新实现该类,则无法安全地完成此操作,因为当用户开始和完成编辑时,对象代码的内部会调整文本对齐方式。

最接近您想要做的事情是使用三个位置调整来水平移动文本,但这不会影响对齐,只会影响绝对位置,即使这样也只会在用户键入时影响。

如果您想尝试此操作,请查找 searchTestPositionAdjustment、setPositionAdjustment:forSearchBarIcon: 和 searchFieldBackgroundPositionAdjustment。不过,我认为它对您没有多大用处。

-灰

于 2014-02-22T08:43:02.327 回答
1

为时已晚,但如果有人仍然想知道解决方案,那么你可以按照这个。

UITextField *searchTextField = [searchBarController.searchBar valueForKey:@"_searchField"];

您可以使用上面的代码获取搜索字段。现在只需使用您想要使用的属性,例如。

searchTextField.layer.cornerRadius = 10.0f;
searchTextField.textAlignment = NSTextAlignmentRight;
于 2016-02-11T09:39:21.600 回答
0

我有办法解决这个问题。它有点hacky而且不是很整洁,但它确实有用。

由于UISearchBar它本身不允许您编辑占位符,因此我在其UITextField下方设置了一个并通过执行以下操作将其禁用:

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{

  if([touch.view isDescendantOfView:self.placeHolderTextField]){
    return NO;
  }

  return YES;
}

注意:不要忘记包含<UIGestureRecognizerDelegate>在您的 .h 文件中。但是,如果这不起作用,您可以随时使用[self.view sendSubViewToBack:self.placeholderTextField];

接下来,我刚刚设置了要在其上显示占位符以及何时不显示的事件。在 中viewDidLoad,我只是在打电话self.placeHolderTextFiew.placeholder = @"search"

而在

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if(searchText.length > 0){
      self.placeHolderTextfield.placeholder = @"";
    }  else{
       self.placeHolderTextfield.placeholder = @"search";
    }
}

再次注意:确保包含<UISearchBarDelegate>在您的 .h 文件中以使其正常工作。

tableView也在使用 a ,所以当DidSelectRowAtIndexPath调用该方法时,我还将占位符设置为空字符串。

希望这可以帮助。

于 2014-09-13T19:46:40.840 回答
-2

设置文本右对齐的方法

搜索栏->属性检查器->搜索文本->自定义偏移量->水平(按要求设置)

于 2014-06-05T06:37:17.407 回答
-2

你也可以这样尝试.. searchbar.placeholder = @"Hai.. whitespace";

于 2014-02-13T06:37:47.357 回答
-3

在玩了 UISearchBar 的子视图后,我找到了这个解决方案,它适用于 iOS 6 和 iOS 7

//hacking search bar
UITextField *searchField;
for (UIView *subview in self.searchBar.subviews)
{

    //this will work in iOS 7
    for (id sub in subview.subviews) {
        if([NSStringFromClass([sub class]) isEqualToString:@"UISearchBarTextField"])
        {
            [sub setTextAlignment:NSTextAlignmentRight];
        }
    }
    //this will work for less than iOS 7
    if ([subview isKindOfClass:[UITextField class]]) {
        searchField = (UITextField *)subview;
        break;
    }
}
//for less than iOS 7
if (searchField) {
    searchField.textAlignment = NSTextAlignmentRight;
}
于 2013-10-24T01:29:36.653 回答