Search code examples
macosswift4nstextfield

Passing a value from inputField to NSTextField


I'd like to pass string value from one NSTextField to another NSTextField pressing a button. I used for this for-in loop. I need to pass a value from inputField to visibleText1, then to visibleText2 and then to visibleText3. But it doesn't work.

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var inputField: NSTextField!
    @IBOutlet weak var visibleText1: NSTextField!
    @IBOutlet weak var visibleText2: NSTextField!
    @IBOutlet weak var visibleText3: NSTextField!

    func applicationDidFinishLaunching(aNotification: NSNotification) { }
    func applicationWillTerminate(aNotification: NSNotification) { }

    @IBAction func applyButton(sender: AnyObject) {      
        for u in (visibleText1.stringValue...visibleText3.stringValue) {
            visibleText.stringValue[u] = inputField.stringValue
            inputField.stringValue = ""
        }
    }
}

Xcode gives me an error:

// Type 'ClosedInterval<String>' does not conform to protocol 'SequenceType' 

How how to do it right?

enter image description here


Solution

  • No you can't do that because you can't create a range of string values of different text fields.

    You could make an array of the three fields and enumerate that:

    @IBAction func applyButton(sender: AnyObject) {      
        for field in [visibleText1, visibleText2, visibleText3] {
            field.stringValue = inputField.stringValue
        }
        inputField.stringValue = ""
    }
    

    or with the forEach function

    @IBAction func applyButton(sender: AnyObject) {      
        [visibleText1, visibleText2, visibleText3].forEach {
            $0.stringValue = inputField.stringValue
        }
        inputField.stringValue = ""
    }
    

    Resetting the inputField in the repeat loop would always apply an empty string after the first iteration.