从从storyboard连接的UITextField到Swift视图控制器文件的输入 [英] Input from UITextField connected from storyboard to Swift view controller file
问题描述
使用Swift,如何从 UITextField
?
获得输入在我的Main.storyboard中,我从预制组件中选择了一个文本字段并将其拖放到我的故事板上。
现在如何在ViewController.swift中访问它的值?
我目前正在做什么:
ViewController.swift文件。然后在弹出框中选择outlet并将其命名为myInput。
然后在另一个函数中,通过使用 self.myInput.text
。
这是唯一的方法来访问它的输入?我的方法遵循Swift约定?
是的,你创建一个 IBOutlet
从故事板并引用它使用 self.myInput.text
是一个标准的方式访问此字段在Swift。
至于是否使用 self.myInput
与 myInput
,我更喜欢总是写 self
,因为这是非常明显的变量是一个属性,可能会在许多不同的地方(相对于局部var)。此外,一旦你有 self
那里,你不必担心引入相同的名称的局部变量或更改,如果你复制并粘贴一段代码到需要自我的闭合。
Using Swift, how do I get the input from a UITextField
?
In my Main.storyboard, I have chosen a "Text Field" from the premade components and dragged it onto my storyboard.
Now how can I access its value in my ViewController.swift?
What I'm currently doing:
I ctrl+drag the text field into my ViewController.swift file. Then in the popup-box I choose "outlet" and name it "myInput".
Then in another function, I access its value by using self.myInput.text
.
Is this the only way to access its input? Is my approach following Swift conventions?
Yes, your approach of creating an IBOutlet
from the storyboard and referencing it using self.myInput.text
is a standard way of accessing this field in Swift.
As for whether to use self.myInput
vs. myInput
, I prefer to always write self
because it is very obvious that the variable is a property and will probably be changed in many different places (opposed to a local var). Also, once you have self
there, you don't have to worry about introducing local vars with the same name or making changes if you copy and paste a block of code into a closure that requires self.
这篇关于从从storyboard连接的UITextField到Swift视图控制器文件的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!