ios 如何左对齐 UISearchBar 占位符文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20383827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:37:35  来源:igfitidea点击:

How to left align UISearchBar placeholder text

iosobjective-cuiimageviewuisearchbar

提问by Chandler De Angelis

This is the searchbar that the designers want me to create

这是设计师要我创建的搜索栏

I need to make a custom search bar like this. The problem I am having is left aligning the placeholder text, as well as placing the search icon in the right. I have a png of the search icon that I have tried to use in an UIImageView, and set that UIImageViewas the rightViewof the UISearchBar's UITextField. This solution has not worked, and I ran out of ideas. Does anyone have a solution?

我需要制作一个这样的自定义搜索栏。我遇到的问题是左对齐占位符文本,以及将搜索图标放在右边。我有搜索图标的PNG,我曾尝试使用在UIImageView,并设置UIImageViewrightView在的UISearchBarUITextField。这个解决方案没有奏效,我的想法用完了。有没有人有办法解决吗?

采纳答案by paulrehkugler

Don't use a UISearchBarif you need to do these kinds of customizations. You'll have to make your own using a UITextFieldand a UIImageView, and responding to the delegate calls.

UISearchBar如果您需要进行这些类型的自定义,请不要使用 a 。您必须自己使用 aUITextField和 a UIImageView,并响应委托调用。

回答by Mounika Vangala

SWIFT 3

斯威夫特 3

swift 3 does not allow to override placeholder property. This is the modified version of Drix answer.

swift 3 不允许覆盖占位符属性。这是 Drix 答案的修改版本。

func setPlaceHolder(placeholder: String)-> String
   {

       var text = placeholder
           if text.characters.last! != " " {

               //                         define a max size

               let maxSize = CGSize(width: UIScreen.main.bounds.size.width - 97, height: 40)

               //                        let maxSize = CGSizeMake(self.bounds.size.width - 92, 40)
               // get the size of the text
               let widthText = text.boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:nil, context:nil).size.width
               // get the size of one space
               let widthSpace = " ".boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:nil, context:nil).size.width
               let spaces = floor((maxSize.width - widthText) / widthSpace)
               // add the spaces
               let newText = text + ((Array(repeating: " ", count: Int(spaces)).joined(separator: "")))
               // apply the new text if nescessary
               if newText != text {
                   return newText
               }

           }

       return placeholder;
   }

and call the function as :

并将函数调用为:

searchBar.placeholder = self.setPlaceHolder(placeholder: "your placeholder text");

回答by Adriano Spadoni

Based in Mohittomar answer, as asked by @DevC to add spaces to the end of the place holder, here the code in swift:

基于 Mohittomar 的回答,正如@DevC 所要求的那样在占位符的末尾添加空格,这里是 swift 中的代码:

I subclass placeholder in the UISearchBar, after set the value, I check if the last character is a space. then get the size of one space and how many spaces I need to add to align left.

我将 UISearchBar 中的占位符子类化,设置值后,我检查最后一个字符是否为空格。然后获取一个空格的大小以及我需要添加多少空格才能左对齐。

class SearchBar: UISearchBar, UISearchBarDelegate {
override var placeholder:String? {
    didSet {
        if let text = placeholder {
            if text.last != " " {

// get the font attribute
                let attr = UITextField.s_appearanceWhenContainedIn(SearchBar).defaultTextAttributes
// define a max size
                let maxSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width - 60, 40)
// get the size of the text
                var widthText = text.boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
// get the size of one space
                var widthSpace = " ".boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
                let spaces = floor((maxSize.width - widthText) / widthSpace)
// add the spaces
                let newText = text + (" " * spaces)
// apply the new text if nescessary
                if newText != text {
                    placeholder = newText
                }
            }
        }
    }
}

回答by fede1608

A working solution for Drix answer

Drix 答案的有效解决方案

import Foundation
import UIKit

class LeftAlignedSearchBar: UISearchBar, UISearchBarDelegate {
    override var placeholder:String? {
        didSet {
            if #available(iOS 9.0, *) {
                if let text = placeholder {
                    if text.characters.last! != " " {
                        // get the font attribute
                        let attr = UITextField.appearanceWhenContainedInInstancesOfClasses([LeftAlignedSearchBar.self]).defaultTextAttributes
                        // define a max size
                        let maxSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width - 87, 40)
//                        let maxSize = CGSizeMake(self.bounds.size.width - 92, 40)
                        // get the size of the text
                        let widthText = text.boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
                        // get the size of one space
                        let widthSpace = " ".boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
                        let spaces = floor((maxSize.width - widthText) / widthSpace)
                        // add the spaces
                        let newText = text + ((Array(count: Int(spaces), repeatedValue: " ").joinWithSeparator("")))
                        // apply the new text if nescessary
                        if newText != text {
                            placeholder = newText
                        }
                    }
                }
            }
        }
    }
}

This method appearanceWhenContainedInInstancesOfClasses is not available in iOS 8, there is a workaround for iOS 8 here

这种方法appearanceWhenContainedInInstancesOfClasses是不是在iOS的8个可用的,有针对iOS 8一种变通方法在这里

回答by Lion

A working swift 3 solution for Drix answer:

Drix 的一个有效的 swift 3 解决方案:

import Foundation
    import UIKit

    class LeftAlignedSearchBar: UISearchBar, UISearchBarDelegate {
        override var placeholder:String? {
            didSet {
                if #available(iOS 9.0, *) {

                    if let text = placeholder {
                        if text.characters.last! != " " {
                            // get the font attribute
                            let attr = UITextField.appearance(whenContainedInInstancesOf: [LeftAlignedSearchBar.self]).defaultTextAttributes
                            // define a max size
                            let maxSize = CGSize(width: UIScreen.main.bounds.size.width - 87, height: 40)
                            // let maxSize = CGSize(width:self.bounds.size.width - 92,height: 40)
                            // get the size of the text
                            let widthText = text.boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:attr, context:nil).size.width
                            // get the size of one space
                            let widthSpace = " ".boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:attr, context:nil).size.width
                            let spaces = floor((maxSize.width - widthText) / widthSpace)
                            // add the spaces
                            let newText = text + ((Array(repeating: " ", count: Int(spaces)).joined(separator: "")))
                            // apply the new text if nescessary
                            if newText != text {
                                placeholder = newText
                            }
                        }
                    }
                }
            }
        }

        /*
        // Only override draw() if you perform custom drawing.
        // An empty implementation adversely affects performance during animation.
        override func draw(_ rect: CGRect) {
            // Drawing code
        }
        */

    }

回答by cain

it could be done from story board there is combo box with name semantic on attribute inspector of search bar if you set it to force right to left its done you have right align search bar and it has a similar thing for aligning from left

它可以从故事板完成,搜索栏的属性检查器上有一个带有名称语义的组合框,如果您将其设置为强制从右到左完成,您可以右对齐搜索栏,并且它具有类似的从左对齐的功能

回答by Vlkam

Version for Xamarin

Xamarin 版本

SearchBar.MovePlaceHolderLeft();


public static void MovePlaceHolderLeft(this UISearchBar  searchbar)
{
    NSAttributedString text = new NSAttributedString(searchbar.Placeholder ?? "");
    // define a max size
    var maxSize = new CGSize(width: UIScreen.MainScreen.Bounds.Size.Width - 97, height: 40);
    // get the size of the text
    var widthText = text.GetBoundingRect(maxSize, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size.Width;
    // get the size of one space
    var widthSpace = new NSAttributedString(" ").GetBoundingRect(maxSize, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size.Width;
    var spaces = Math.Floor((maxSize.Width - widthText) / widthSpace);
    // add the spaces
    string newText = searchbar.Placeholder;
    for (double i = 0; i < spaces; i++)
    {
        newText += " ";
    }
    searchbar.Placeholder = newText;
}

回答by ameunier

If you want your control to respond exactly how you want, you should probably make your own custom control. This control could be separated in three parts :

如果您希望您的控件完全按照您的意愿做出响应,您可能应该制作自己的自定义控件。该控件可以分为三个部分:

  1. a background UIImageView
  2. a UITextField
  3. a UIButtonfor the the search icon if you want the user to interact with it
  1. 背景 UIImageView
  2. 一种 UITextField
  3. aUIButton用于搜索图标,如果您希望用户与之交互

The easiest way to do that is probably to create a new class MySearchBar, with the three parts in the private interface :

最简单的方法可能是创建一个新类MySearchBar,在私有接口中包含三个部分:

@interface MySearchBar ()
@property (nonatomic, strong) UISearchBar* searchBar;
@property (nonatomic, strong) UITextField* textField;
@property (nonatomic, strong) UIButton* button;
@end

In your MySearchBar, you can create your component, customize it, add a better look & feel. To get back the search result, your control can have a delegate id<UISearchBarDelegate>(your UIViewController) which will basically simulate having a standard UISearchBar.

在你的 中MySearchBar,你可以创建你的组件,自定义它,添加更好的外观和感觉。为了取回搜索结果,您的控件可以有一个委托id<UISearchBarDelegate>(您的UIViewController),它基本上模拟拥有一个标准的 UISearchBar。

What remains is to create your MySearchBarin your controller and set the delegate to your view controller. The messages from the UISearchBarDelegatecan either go to your MySearchBarto filter or do pre-treatment before sending to your UIViewController, or go directly to your UIViewController.

剩下的就是MySearchBar在您的控制器中创建您的并将委托设置为您的视图控制器。来自 的消息UISearchBarDelegate可以先到您MySearchBar的过滤器或在发送到您UIViewControllerUIViewController.

回答by Mohit Tomar

No need to any customization just do it...

无需任何定制就可以了...

    searchBar.placeholder=@"Search                                                        ";

searchbar has centeral text alignment for its place-hoder , so just give some big text. and if you text is small then just use some space after place-holder text.

搜索栏的 place-hoder 具有居中文本对齐方式,因此只需提供一些大文本即可。如果您的文本很小,那么只需在占位符文本后使用一些空间。

回答by Faran Rasheed

It's too late, but if anyone is still wondering the solution, then you can follow this.

为时已晚,但是如果有人仍然想知道解决方案,那么您可以按照此操作。

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

You can get the search field using above code. Now simply use the properties you want to use, like.

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

searchTextField.layer.cornerRadius = 10.0f;
searchTextField.textAlignment = NSTextAlignmentLeft;

PS. Text alignment property is used for text and placeholder both. Thanks.

附注。文本对齐属性用于文本和占位符。谢谢。