简体   繁体   中英

Changing the text in a programatically text field

I'm creating text fields programatically inside a scroll view these are spaced out and filled with numbers. I would like the option to change the numbers at any point. I can obviously re-run the code changing for example

String (i+1)

to

String (i+7)

But this just creates another text box over the original. Is there a way to either delete the original text boxes before creating new ones. Or edit the text inside the original boxes. I obviously do not have an outlet as they are created programatically.

Thank you for your time

xcode 8.1 swift 3.0 for OSX not IOS

for i in 0..<18 {
    let barNumberTextColor = NSColor(red: 0.2, green: 0.0, blue: 0.0, alpha: 1.0)
    let barNumberTextFont = NSFont(name: "Lucida Grande Bold", size: 12.0)
    barNumberTextField.font = barNumberTextFont
    barNumberTextField.textColor = barNumberTextColor
    barNumberTextField = NSTextField(labelWithString: String (i+1))
    barNumberTextField.frame = NSMakeRect(CGFloat(i)*320,3,30,20)
    if (i >= 0 && i < 16) {
        self.addSubview(barNumberTextField)
    }

}//eo for

Removing textfield from scroll view:

self.barNumberTextField.removeFromSuperview()

Changing textFieldValue:

self.barNumberTextField.stringValue = "New string"

In the loop you can add a tag to the TextField, like this:

barNumberTextField.tag = i + 1

Then, when you need to change its content you can capture the TextField by its tag using:

let myTextField = self.viewWithTag(x) where x is the tag of the textfield you need to edit.

At this point this will solve your issue: myTextField.text = "whatever"

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