ChallengerGuy
ChallengerGuy

Reputation: 2395

How do I create a separate swift file and call the function in it later?

I have an Xcode project in Swift I'm creating. In my main View Controller, it is taking a long time to load because of all the functions in it. I think that if I create a swift file and call this later, it will speed up my project and not have as long of code in my main View Controller. I'm trying to create a separate Swift file that will have some functions in it, and then call this into the main View Controller. I created a Swift file and called it 'sunday.swift'. A piece of the code that will got into it is:

import Foundation
import UIKit

extension UIView {
    func codedSundayButtons(){
    //Chore 1 (RED)
    ButtonSunChore1R.viewWithTag(0)
    ButtonSunChore1R.setBackgroundImage(sunC1R, forState: .Normal)
    ButtonSunChore1R.addTarget(self, action: "ButtonSunChore1Ra:", forControlEvents: UIControlEvents.TouchUpInside)
    addSubview(ButtonSunChore1R)

    //Chore 1 (YELLOW)
    ButtonSunChore1Y.viewWithTag(1)
    ButtonSunChore1Y.setBackgroundImage(sunC1Y, forState: .Normal)
    ButtonSunChore1Y.addTarget(self, action: "ButtonSunChore1Ya:", forControlEvents: UIControlEvents.TouchUpInside)
    addSubview(ButtonSunChore1Y)
    }
}

Within the newly created Swift file, I will create the button actions, etc. and a lot more buttons. How do I call this sunday.swift file and codedSundayButtons function in my main View Controller.

I've tried writing this question in the correct format so I don't get flagged for doing it wrong and not be able to post anymore questions.

Upvotes: 0

Views: 1300

Answers (1)

Caleb
Caleb

Reputation: 5626

Most likely, this is not the problem for the slow loading.

Anyways here is how you would accomplish what you are wanting to do:

Create a file called LanguageExtensions.swift

extension UIView {
    func codedSundayButtons(#firstButton: UIButton, secondButton: UIButton){
        //Chore 1 (RED)
        ButtonSunChore1R.viewWithTag(0)
        ButtonSunChore1R.setBackgroundImage(sunC1R, forState: .Normal)
        ButtonSunChore1R.addTarget(self, action: "ButtonSunChore1Ra:", forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(ButtonSunChore1R)

        //Chore 1 (YELLOW)
        ButtonSunChore1Y.viewWithTag(1)
        ButtonSunChore1Y.setBackgroundImage(sunC1Y, forState: .Normal)
        ButtonSunChore1Y.addTarget(self, action: "ButtonSunChore1Ya:", forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(ButtonSunChore1Y)
    }
}

And call it using: yourView.codedSundayButtons(firstButton: ButtonSunChore1R, secondButton: ButtonSunChore1Y)

Upvotes: 1

Related Questions