How to left align UISearchBar placeholder text

前端 未结 10 776
孤独总比滥情好
孤独总比滥情好 2020-12-17 17:04

\"This

I need to make a custom search bar like this. Th

10条回答
  •  北海茫月
    2020-12-17 17:11

    Based in Mohittomar answer, as asked by @DevC to add spaces to the end of the place holder, here the code in 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.

    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
                    }
                }
            }
        }
    }
    

提交回复
热议问题