SHARE
TWEET

Untitled

a guest Jun 25th, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import UIKit
  2.  
  3. class ViewController: UIViewController {
  4.  
  5.     var searchBar: UISearchBar!
  6.    
  7.     var placeholderWidth: CGFloat!
  8.    
  9.     override func viewDidLoad() {
  10.         super.viewDidLoad()
  11.        
  12.         searchBar = UISearchBar()
  13.         view.addSubview(self.searchBar)
  14.        
  15.         searchBar.placeholder = "placeholder"
  16.        
  17.         if let textFieldOfSearchBar = searchBar.value(forKey: "searchField") as? UITextField {
  18.             textFieldOfSearchBar.textAlignment = .center
  19.             placeholderWidth = textFieldOfSearchBar.attributedPlaceholder?.size().width
  20.         }
  21.        
  22.         setupAutoLayout()
  23.        
  24.     }
  25.    
  26.     override func viewDidLayoutSubviews() {
  27.         let offSet = UIOffset(horizontal: searchBar.frame.width / 2 - placeholderWidth  , vertical: 0)
  28.        
  29.         searchBar.setPositionAdjustment(offSet, for: .search)
  30.     }
  31.    
  32.     private func setupAutoLayout() {
  33.         searchBar.translatesAutoresizingMaskIntoConstraints = false
  34.         searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  35.         searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
  36.         searchBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 50) .isActive = true
  37.         searchBar.heightAnchor.constraint(equalToConstant: 50).isActive = true
  38.     }
  39.    
  40. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top