I
I
Ivan Drozhzhin2021-08-01 10:25:07
Swift
Ivan Drozhzhin, 2021-08-01 10:25:07

How to remove double image from bar button?

Hello!
I am writing an application that displays images of dogs with tiles through a CollectionView. Task: add a function to switch the view from 2 tiles in a row to 3 tiles.

In order to make such a switch, I made a Bar Button Item, assigned the image square.grid.2x2.fill to it. I
wrote a function that changes the display and sets a new image for the button. Everything works, but there was a problem that I could not solve on my own - when you click on the button, a second image appears and the size of the button changes:

Here are screenshots of the button: https://drive.google.com/drive/folders/1uY82VNgPMn... I

create the button and insert with code, not through storyboard

override func viewDidLoad() {
            super.viewDidLoad()
            let button: UIButton = UIButton(type: .custom)
            button.setImage(UIImage(systemName: "square.grid.2x2.fill"), for: .normal)
            button.addTarget(self, action: #selector(PhotosCollectionViewController.layoutChoose), for: .touchUpInside)
            let barButton = UIBarButtonItem(customView: button)
            self.navigationItem.rightBarButtonItem = barButton


Next, the action function on the button:

@objc func layoutChoose(sender: UIButton) {
            if itemsPerRow == 3 {
                sender.setBackgroundImage(UIImage(systemName: "square.grid.3x2.fill"), for: .normal)
                itemsPerRow = 2
                collectionView.reloadData()
            } else {
                sender.setBackgroundImage(UIImage(systemName: "square.grid.2x2.fill"), for: .normal)
                itemsPerRow = 3
                collectionView.reloadData()
            }
        }


I tried to create a button in the storyboard and set functions through the outlet, but the result is the same
@IBOutlet weak var twoSquares: UIBarButtonItem!
@IBAction func twoSquersPressed(_ sender: UIBarButtonItem) {
        if itemsPerRow == 3 {
            twoSquares.setBackgroundImage(UIImage(systemName: "square.grid.3x2.fill"), for: .normal, barMetrics: .default)
            itemsPerRow = 2
            collectionView.reloadData()
        } else {
            twoSquares.setBackgroundImage(UIImage(systemName: "square.grid.2x2.fill"), for: .normal, barMetrics: .default)
            itemsPerRow = 3
            collectionView.reloadData()

        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
timoninas1, 2021-08-20
@timoninas1

You set backroundImage, and you need to put a new photo in the same image BarButtonItem parameter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question