Can the height of the UISearchbar TextField be modified?

31.4k Views Asked by At

I'm testing out my UI and I find the search bar a little bit too narrow for my liking. I also want to make sure people with poorer vision or poorer manual dexterity have no issues bringing up the interface they want.

So, what I would like to do is Adjust the height of the UITextfield inside UISearchbar.

What I have tried: 1. In Storyboard, add UISearchbar Height constraint - Results: the searchbar size increases, but the UITextField inside stays the same.

  1. Access the UITextField inside UISearchbar and modify its height - Results: The console output shows that the parameter is modified, but on screen, the UITextField height remains the same.

Note - I can modify other parameters of the UITextField using method 2 and the change is reflected on screen so I know I am getting to the UITextField

Code for Method 2, put in viewDidLoad() of ViewController where UISearchbar is located:

for tempView in (self.roomInfoSearchBar.subviews[0] as! UIView).subviews as! [UIView]
{
  if let tV = tempView as? UITextField
  {
    var currentFrameRect = tV.frame
    currentFrameRect.size.height = 80
    //tV.layer.backgroundColor = UIColor.blueColor().CGColor  //This works fine
    //tV.layer.cornerRadius = 5  //This works fine
    //tV.font = UIFont(name: "Courier", size: 40)  //This works fine
    println(tV.frame.height)  //console output:0.0
    tV.frame = currentFrameRect
    println(tV.frame) //console output:(0.0, 0.0, 0.0, 80.0)
    println(currentFrameRect) //console output:(0.0, 0.0, 0.0, 80.0) - redundant, just checking
    println(tV.frame.height) //console output:80.0 - it says 80, but screen shows searchbar definitely not 80.
  }
}

I think it has something to do with autolayout somehow being able to disregard parameters regardless of where it is set. I would like to continue to use autolayout since it does a lot of work for me, but I wish it would behave like it does in Storyboard where when a user sets a setting it will use those parameters in its autolayout and complain when it can't as opposed to just ignoring the setting without feedback.

Edit:

In response to Mahesh. I'm don't know much objective C++ but I tried my best to convert what you wrote into swift. This is what I have:

(Inside my viewcontroller.swift)

func viewDIdLayoutSubviews()
{
  super.viewDidLayoutSubviews()
  self.roomInfoSearchBar.layoutSubviews()

  var topPadding: Float = 5.0
  for view in (self.roomInfoSearchBar.subviews[0] as! UIView).subviews as! [UIView]
  {
    if let tfView = view as? UITextField
    {
      var calcheight = self.roomInfoSearchBar.frame.size.height - 10
      tfView.frame = CGRectMake(tfView.frame.origin.x, CGFloat(topPadding), tfView.frame.size.width, self.roomInfoSearchBar.frame.size.height - CGFloat(topPadding * 2))
    }
  }
}

I've kept my code for getting to the textfield since I had some issues converting your code to swift. For the CGRectMake - swift complained about various types including that topPadding wasn't a CGFloat and for the last variable (Y size), again it did not like mixing CGFloat with Float so I had to change that too.

Unfortunately, it does not appear to work. I changed the UISearchbar height to 80 in storyboard and I just got a very tall searchbar with the textfield covering about 1/3 of the total height.

Edit #2: Incorporating Yuyutsu and corrected version of Mahesh code. Still not perfect, but closer. Yuyutsu's code works but as mentioned in my comments, the field does not center, the resize is also visible (jump from height A to height B) when the view is first loaded. One additional deficiency is that because the resize is done at viewDidAppear once the orientation changes, the field returns to the intrinsic size.

My code based on Yuyutsu's:

  override func viewDidAppear(animated: Bool)
  {
    super.viewDidAppear(animated)
    var roomInfoSearchBarFrame = roomInfoSearchBar.frame
    var newHeight: CGFloat = 60
    for subView in roomInfoSearchBar.subviews
    {
      for subsubView in subView.subviews
      {
        if let textField = subsubView as? UITextField
        {
          var currentTextFieldFrame = textField.frame
          var recenteredY = (roomInfoSearchBarFrame.height - newHeight)/2
          var newTextFieldFrame = CGRectMake(textField.frame.minX, recenteredY, textField.frame.width, newHeight)

          textField.frame = newTextFieldFrame
          textField.borderStyle = UITextBorderStyle.RoundedRect
          textField.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
          //textField.backgroundColor = UIColor.redColor()
          //                    textField.font = UIFont.systemFontOfSize(20)
        }
      }
    }
  }

Looking at Yuyutsu's code I wanted to know where else I could put this adjustment and I came across link via another stackoverflow post. Based on what I read, I saw that Mahesh's answer should work. This is where I realized why it wasn't working - I needed to override func viewWillLayoutSubviews().

Current code: Keeps size with orientation change. But size jump still visible (it shouldn't be visible)

  override func viewWillLayoutSubviews()
  {
    super.viewWillLayoutSubviews()
    var roomInfoSearchBarFrame = roomInfoSearchBar.frame
    var newHeight: CGFloat = 60
    for subView in roomInfoSearchBar.subviews
    {
      for subsubView in subView.subviews
      {
        if let textField = subsubView as? UITextField
        {
          var currentTextFieldFrame = textField.frame
          var recenteredY = (roomInfoSearchBarFrame.height - newHeight)/2
          var newTextFieldFrame = CGRectMake(textField.frame.minX, recenteredY, textField.frame.width, newHeight)

          textField.frame = newTextFieldFrame
          textField.borderStyle = UITextBorderStyle.RoundedRect
          textField.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
          //textField.backgroundColor = UIColor.redColor()
          //                    textField.font = UIFont.systemFontOfSize(20)
        }
      }
    }
  }

So right now, the only thing left is to try and make it so the textfield is the set size prior to the view being visible so there is no size shift that is visible to the user.

Final Edit: Fully working code With Yuyutsu's additional help, code below does everything I want - starts off at the set size, field is centered, deals with rotation fine.

  override func viewDidLayoutSubviews()
  {
    super.viewDidLayoutSubviews()
    self.roomInfoSearchBar.layoutIfNeeded()
    self.roomInfoSearchBar.layoutSubviews()

    var roomInfoSearchBarFrame = roomInfoSearchBar.frame
    var newHeight: CGFloat = 60 //desired textField Height.
    for subView in roomInfoSearchBar.subviews
    {
      for subsubView in subView.subviews
      {
        if let textField = subsubView as? UITextField
        {
          var currentTextFieldBounds = textField.bounds
          currentTextFieldBounds.size.height = newHeight
          textField.bounds = currentTextFieldBounds
          textField.borderStyle = UITextBorderStyle.RoundedRect
          //textField.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
        }
      }
    }
  }

Thanks Yuyutsu. Thanks Mahesh for pretty much coming up with the final solution right from the start, just missing a few critical bits.

10

There are 10 best solutions below

7
On BEST ANSWER
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        for subView in searchBars.subviews  {
            for subsubView in subView.subviews  {
                if let textField = subsubView as? UITextField {
                     var bounds: CGRect
                bounds = textField.frame
                bounds.size.height = 35 //(set height whatever you want)
                    textField.bounds = bounds
                    textField.borderStyle = UITextBorderStyle.RoundedRect
//                    textField.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
                    textField.backgroundColor = UIColor.redColor()
//                    textField.font = UIFont.systemFontOfSize(20)
                }
            }
        }

    }

This might helps you :)

6
On

You can change the height of the inner text field try this code.

step 1) set constraint to increase your UISearchBar height then make outlet of search bar and write down this code in view controller.

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    [self.searchBar layoutSubviews];

    float topPadding = 5.0;
    for(UIView *view in self.searchBar.subviews)
    {
        for(UITextField *textfield in view.subviews)
        {
            if ([textfield isKindOfClass:[UITextField class]]) {
                textfield.frame = CGRectMake(textfield.frame.origin.x, topPadding, textfield.frame.size.width, (self.searchBar.frame.size.height - (topPadding * 2)));
            }
        }
    }
}

also if you want to change anything else in the search bar then you can find the exact base element like UILabel, UIImage and UIView inside the UITextField subviews and can change the frame and image and other properties also. Thanks.

EDIT:

as you asked in swift am writing it in swift. i think you are trying something wrong. please try this.

func viewDIdLayoutSubviews()
{
    super.viewDidLayoutSubviews()
    self.roomInfoSearchBar.layoutSubviews()

    var topPadding: Float = 5.0
    for view in self.roomInfoSearchBar.subviews as [UIView] 
    {
        for viewNew in view.subviews as [UIView] 
        {
            if viewNew.isKindOfClass(UITextField) 
            {
                viewNew.frame = CGRectMake(viewNew.frame.origin.x, CGFloat(topPadding), viewNew.frame.size.width, self.roomInfoSearchBar.frame.size.height - CGFloat(topPadding * 2))
            }
        }
    }
}

you taken the 0 index view as first and last view to be looped. i think thats the problem the code you translated didn't worked. Try once and please reply.

1
On

I did this by positioning the SearchTextField in the UISearchBar container view.

@IBOutlet weak var searchBarView: UISearchBar!
override func viewDidLoad() {
    super.viewDidLoad()
    
    searchBarView.searchTextField.translatesAutoresizingMaskIntoConstraints = false
    
    NSLayoutConstraint.activate([
        searchBarView.searchTextField.leadingAnchor.constraint(equalTo: searchBarView.leadingAnchor, constant: 20),
        searchBarView.searchTextField.trailingAnchor.constraint(equalTo: searchBarView.trailingAnchor, constant: -20),
        searchBarView.searchTextField.topAnchor.constraint(equalTo: searchBarView.topAnchor, constant: 20),
        searchBarView.searchTextField.bottomAnchor.constraint(equalTo: searchBarView.bottomAnchor, constant: -20),
        searchBarView.searchTextField.heightAnchor.constraint(equalToConstant: 65)
    ])
}

You can change the values according to the size and positioning you want.

Result:

Custom height to SearchBarTextField

0
On

This is the correct Swift 4.0 answer on how to change the height of a UISearchBar:

  let image = getImageWithColor(color: UIColor.clear, size: CGSize(width: 1, height: 40))
  searchBar.setSearchFieldBackgroundImage(image, for: .normal)

Using following method:

  func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }

Tested on 4th. June. 2018

0
On

For swift 5.0 it works good:

extension UIImage {
    class func image(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { rendererContext in
            color.setFill()
            rendererContext.fill(CGRect(origin: .zero, size: size))
        }
    }
}

extension UISearchBar {
    func customize() {
        setSearchFieldBackgroundImage(UIImage.image(color: .clear, size: CGSize(width: 1, height: 44)), for: .normal)

        // other settings
        searchBarStyle = .minimal
        searchTextPositionAdjustment = UIOffset(horizontal: 0, vertical: 0)
        tintColor = .black
        backgroundColor = .whiteBackground
        searchTextField.leftViewMode = .never
        searchTextField.textColor = .black
        searchTextField.backgroundColor = UIColor.lightGrayBackground
        searchTextField.layer.borderColor = UIColor.gray.cgColor
        searchTextField.cornerRadius = 22
        searchTextField.borderWidth = 0.5
    }
}

Just use:

let searchBar = UISearchBar()
searchBar.customize()
0
On

MonoTouch version of wj2061 answer:

UIImage GetImageWithColor(UIColor color, CGSize size)
{
    var rect = new CGRect(0, 0, size.Width, size.Height);
    var path = UIBezierPath.FromRoundedRect(rect, 5);
    UIGraphics.BeginImageContextWithOptions(size, false, 0);
    color.SetFill();
    path.Fill();
    var image = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();
    return image;
}

var image = GetImageWithColor(UIColor.LightGray, new CGSize(20, 20));
searchBar.SetSearchFieldBackgroundImage(image, UIControlState.Normal);
0
On

Update for Swift 4.2/iOS 12.1:

let newHeight : CGFloat = 45
for subview in searchBar.subviews {
    for subsubview in subview.subviews {
        if let textField = subsubview as? UITextField {
            var currentTextfieldBounds = textField.bounds
            currentTextfieldBounds.size.height = newHeight
            textField.bounds = currentTextfieldBounds
            textField.borderStyle = .roundedRect
            textField.contentVerticalAlignment = .center
        }
    }
}
0
On

Based on thelearner's answer here's the code for Swift 5.* :

extension UISearchBar {
    func updateHeight(height: CGFloat, radius: CGFloat = 8.0) {
        let image: UIImage? = UIImage.imageWithColor(color: UIColor.clear, size: CGSize(width: 1, height: height))
        setSearchFieldBackgroundImage(image, for: .normal)
        for subview in self.subviews {
            for subSubViews in subview.subviews {
                if #available(iOS 13.0, *) {
                    for child in subSubViews.subviews {
                        if let textField = child as? UISearchTextField {
                            textField.layer.cornerRadius = radius
                            textField.clipsToBounds = true
                        }
                    }
                    continue
                }
                if let textField = subSubViews as? UITextField {
                    textField.layer.cornerRadius = radius
                    textField.clipsToBounds = true
                }
            }
        }
    }
}

private extension UIImage {
    static func imageWithColor(color: UIColor, size: CGSize) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        guard let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() else {
            return nil
        }
        UIGraphicsEndImageContext()
        return image
    }
}

and here's how we can apply it:

searchBar?.updateHeight(height: 48)

and here's the result: enter image description here

1
On

I've found the accepted answer to be buggy at times.
This is how i've solved the issue of having a custom height for the searchBar: I have set a colour image with the size I want and added it to the searchBar's textField in viewDidLoad:

let image = getImageWithColor(UIColor.whiteColor(), size: CGSizeMake(600, 60))
searchBar.setSearchFieldBackgroundImage(image, forState: .Normal)

Followed with this func taken from here

func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
    var rect = CGRectMake(0, 0, size.width, size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
3
On

If you use :

func setSearchFieldBackgroundImage(backgroundImage: UIImage?, forState state: UIControlState)   

The height of UISearchBar's UITextfield would be the same as the height of the Image.

You can drop in an Image,use it to customize UISearchBar's UITextfield height and backgroundImage.

Or you can use the function below to create a round corner UIImage:

func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
    let rect = CGRectMake(0, 0, size.width, size.height)
    let path = UIBezierPath(roundedRect: rect, cornerRadius: 5.0)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    path.fill()
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

The Width of the UIImage is ignored.But to have a corner radius ,it's better bigger than 10.0.

The code would be look like this:

let image = self.getImageWithColor(UIColor.lightGrayColor(), size: CGSizeMake(20, 20))
searchBar.setSearchFieldBackgroundImage(image, forState: .Normal)