iosswiftios8uisearchbar

Change height of scope buttons of UISearchBar in iOS?


I would like to change the height of the scope buttons for my search bar. I am using adjusted segmented controls and would like to make the scope buttons the same look. Below is a screenshot of my scope buttons and another screenshot of my segmented controls that I would like to match.

This is the code I am using for the segmented control that maybe need to reapply to the search bar scope buttons, but do not know how:

    filterSegmentedControl.frame = CGRect(
        x: filterSegmentedControl.frame.origin.x,
        y: filterSegmentedControl.frame.origin.y,
        width: filterSegmentedControl.frame.size.width,
        height: 22)

My current search bar scope buttons: enter image description here

My segmented control: enter image description here


Solution

  • The segmented control is not exposed from within the UISearchBar interface. So, you cannot control the frame of the segmented control within. If you really want to change the frame height, I dont see any other way of doing it except traversing through the subViews to find the UISegmentedControl and then setting a frame to it manually.

    Here is a little helper extension on UIView which will help you traverse the subview hierarchy inside UISearchBar to find UISegmentedControl.

    extension UIView {
    
        func traverseSubviewForViewOfKind(kind: AnyClass) -> UIView? {
            var matchingView: UIView?
    
            for aSubview in subviews {
                if aSubview.dynamicType == kind {
                    matchingView = aSubview
                    return matchingView
                } else {
                    if let matchingView = aSubview.traverseSubviewForViewOfKind(kind) {
                        return matchingView
                    }
                }
            }
    
            return matchingView
        }
    }
    

    You could then use this method to set frame to the found segmented control manually, which would be something like this,

    if let segmentedControl = searchBar.traverseSubviewForViewOfKind(UISegmentedControl.self) {
      var segmentedControlFrame = segmentedControl.frame
      segmentedControlFrame.size.height = 70
      segmentedControl.frame = segmentedControlFrame
    }