Search code examples
swiftuikituibarbuttonitem

I want to rotate a bar button item - Swift


I encountered with an issue. I want to display 3 buttons, that are used for filtering my tableView. I found an appropriate images from “SF symbols.” Except one, which is the same I used for filtering(bigger to smaller) but is rotated on 180 degrees. I don’t know how to rotate bar button item, so I decided add custom button to bar button item. 


There’s a problem occur – button is very small.

After adding button to bar button item:

enter image description here

I tried to use image configuration, but it’s not very good because it looks different and not with the same spacing.

After configuring button's image:

In the debug view hierarchy I found that symbol config is “Medium”, meanwhile other bar button items have “Body, Large”. But I haven’t found anything how to change it.

enter image description here

I have few questions:

Is there a way to flip bar button item without adding custom button in it?

If the way in the first question impossible, is this real to configure image “dynamically” the same way as other are displayed?


My code:

class viewController: UIViewController {
@IBOutlet var youngToOldfilterButton: UIBarButtonItem!
enter code here
    override func viewDidLoad() {
    let filterButton = UIButton(type: .custom)
    var image = UIImage(systemName: "line.3.horizontal.decrease.circle", withConfiguration: UIImage.SymbolConfiguration(pointSize: 22))
    filterButton.setImage(image, for: .normal)
    filterButton.sizeToFit()
    filterButton.addTarget(self, action: #selector(action), for: .touchUpInside)
    //rotation transform
    filterButton.transform = CGAffineTransform(rotationAngle: 180 * .pi/180)
    youngToOldfilterButton.customView = filterButton
    }

    @objc func action {
        ...
    }
}

Solution

  • symbol config is “Medium”, meanwhile other bar button items have “Body, Large”. But I haven’t found anything how to change it.

    That way is to use a symbol configuration. Your problem is you are using the wrong configuration:

    SymbolConfiguration(pointSize: 22))
    

    Does that say Body, Large? No. You want this:

    SymbolConfiguration(textStyle: .body, scale: .large)
    

    https://developer.apple.com/documentation/uikit/uiimage/symbolconfiguration/3294246-init

    However, the very best solution would likely be to design your own custom symbol image based directly on the "decreasing" image. This takes some time, but it isn't difficult, and you obviously care a lot about the exact thickness and position of the bars, so it might be worth it. Watch https://developer.apple.com/videos/play/wwdc2021/10250 for info.