简体   繁体   中英

Swift Beginner: Linking View Controller and App Delegate

I am a beginner working in Xcode for the first time. I am trying to link an IBAction (in view controller) with a function I have created in App delegate. The problem seems to be with the difference between a .text and String. If you could please refer to the code and try to think of a way that I can link the button I have created (with an IBAction) and the "whatFoodText" function I have created. Please help!

func whatFoodText(whatFood: String, whereFrom: String) -> String {
    if whatFood.text = "Apple" {

linking to

@IBAction func tellMoi(sender: AnyObject) {
    toldMoi.text(whatFoodText)

Your question doesn't make a lot of sense.

In general you shouldn't clutter up your app delegate with "business logic". Keep it light weight, dealing only with methods that handle starting up and shutting down your app and responding to app delegate messages.

You should put the methods that respond to button presses in the view controller those buttons belong to.

It isn't clear what you mean when you say "The problem seems to be with the difference between a .text and String." UI objects like UITextFields, UITextViews, and UILabels have text properties (.text, in swift syntax) that hold the current value in the field. In swift, those properties can be viewed as containing String objects. (They actually contain Cocoa NSString objects, which can be freely converted to/from Swift String objects, so you can largely ignore the difference and just use type casting to convert from one to the other)

If you have a whatFoodText method that needs 2 string inputs, and returns a string as a result, you need to pass it 2 strings.

The line you posted:

toldMoi.text(whatFoodText)

Does not make much sense. You're passing whatFoodText as a parameter. If your goal is to get the result of a call to whatFoodText and store it as the text contents of a field called toldMoi, you need to write your code differently.

Your IBAction method might look like this:

@IBAction func tellMoi(sender: UIButton) 
{
   let string1: String = String(someField.text)
   let string2: String = String(someOtherField.text)

   toldMoi.text = whatFootText(whatFood: string1, whereFrom: string2)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM