How to left align UISearchBar placeholder text

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

\"This

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

10条回答
  •  别那么骄傲
    2020-12-17 17:34

    A working solution for Drix answer

    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

提交回复
热议问题