'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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1