What is the proper way to change the name of a ViewController class in Swift?

10,889

Solution 1

A) If you're using Xcode 9 or later, just select the class name, right click -> Refactor -> Rename

Ex.: class MapViewController: UIViewController - just select the "MapViewController", then right click -> Refactor -> Rename

This will change the name file name, class name and take care of the storyboard class name.

B) If you can't use the method A, then manually rename the class name, file name (.swift), then go to the storyboard and replace the class name of the view controller. You may have issues with the outlets. In this case try to close Xcode and re-launch then remove all IBOutlets and reconnect them again.

Solution 2

  1. Click on the controller name that you want to change.
  2. Inside the class right-click on the class name of the controller.
  3. Now you'll be able to see REFACTOR option.
  4. Click on the refactor you can get RENAME option.
  5. Give whatever name that you want, then click on RENAME.
Share:
10,889

Related videos on Youtube

Austin Berenyi
Author by

Austin Berenyi

Updated on June 04, 2022

Comments

  • Austin Berenyi
    Austin Berenyi over 1 year

    When I change my ViewController class name after it's been created and assigned to a view controller in storyboards I run into problems with the IBOutlets of that view controller, and Xcode does not automatically show the corresponding class in the assistant editor when I click the scene.

    I've changed the name of the actual file, the class declaration within the file, and the class of the view controller in storyboards. Am I missing something else?

    • LinusGeffarth
      LinusGeffarth over 5 years
      You know Xcode does that for you: command+click on the class name, then press Rename at the bottom. It'll show you all the instances it found that it will rename. You should review every single one, because Xcode sometimes finds weirdly unrelated things...