Fady A. Ackad
Fady A. Ackad

Reputation: 125

Want to change the position of the cancel button of the UISearchBar

enter image description here

I want to change the place where the cancel button appears instead of appearing on the right side as in the image I want it to appear on the left side of the search bar.

Upvotes: 3

Views: 836

Answers (2)

SlimeBaron
SlimeBaron

Reputation: 775

One way to put the cancel button on the left is to override the effectiveUserInterfaceLayoutDirection of the Search Bar (iOS 10+).

final class CustomSearchController: UISearchController {
    private var customSearchBar = CustomSearchBar()

    override var searchBar: UISearchBar { customSearchBar }
}

final class CustomSearchBar: UISearchBar {
    override var effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection {
        // Overriding this property swaps the layout at the top level without swapping the layout for the subviews
        super.effectiveUserInterfaceLayoutDirection.flipped
    }

    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        // Set and unset the semanticContentAttribute so the effectiveUserInterfaceLayoutDirection is reevaluated.
        semanticContentAttribute = .forceLeftToRight
        semanticContentAttribute = .unspecified
    }
}

extension UIUserInterfaceLayoutDirection {
    var flipped: UIUserInterfaceLayoutDirection {
        switch self {
        case .rightToLeft: return .leftToRight
        case .leftToRight: return .rightToLeft
        @unknown default: return .rightToLeft
        }
    }
}

This should put the cancel button on the left for LTR languages, and on the right for RTL languages.

Result in English:

enter image description here

Upvotes: 0

Balaji Ramakrishnan
Balaji Ramakrishnan

Reputation: 1949

You cannot change the position of the default SearchBar and Search Display controller.

For your requirement, you need to create your own custom Search Bar with Cancel as you desire.

Hope it helps..

Upvotes: 1

Related Questions