如何从 UISearchBar 移动占位符标签

How can I move the placeholder Label from UISearchBar

我创建了一个简单的扩展 UISearchBar,它比原生的小一点。我已经实现了这段代码:

- (void)layoutSubviews{
    [super layoutSubviews];

   CGRect frame = self.frame;
    if (frame.size.height != 32) {
        frame.size.height = 32;
        self.frame = frame;
    }

    [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#636363"]}];
    UITextField *searchTextField = [self valueForKey:@"_searchField"];
    UILabel *placeholderLabel = [searchTextField valueForKey:@"_placeholderLabel"];

    placeholderLabel.frame = CGRectMake(placeholderLabel.frame.origin.x , placeholderLabel.frame.origin.y + 8 , placeholderLabel.frame.size.width , placeholderLabel.frame.size.height);
    [placeholderLabel setBackgroundColor:[UIColor redColor]];
    [placeholderLabel setFont:[UIFont systemFontOfSize:13]];

    [[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor colorWithHexString:@"#c6c6c6"]];

    self.layer.borderWidth = 1;
    self.layer.borderColor = [[UIColor colorWithHexString:@"#949494"] CGColor];

    [self.layer setMasksToBounds:YES];
    [self.layer setCornerRadius:5];


}

但结果是这样的:

占位符标签仍然不在视图的中心。而且我不知道如何将它移到那里。字体和背景颜色也可以更改,但标签仍然卡在顶部。

您将必须实现自己的控件,因为您将无法移动搜索占位符。

答案是向 UISearchBar 添加一个高度约束并将其设置为 32。魔术完成了,占位符的位置也很好。