How to left align UISearchBar placeholder text

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

\"This

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

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 17:17

    SWIFT 3

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

    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");
    

提交回复
热议问题