ios 来自 UITextField 的输入从故事板连接到 Swift 视图控制器文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27454328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Input from UITextField connected from storyboard to Swift view controller file
提问by Don P
Using Swift, how do I get the input from a UITextField
?
使用 Swift,我如何从 a 获取输入UITextField
?
In my Main.storyboard, I have chosen a "Text Field" from the premade components and dragged it onto my storyboard.
在我的 Main.storyboard 中,我从预制组件中选择了一个“文本字段”并将其拖到我的故事板上。
Now how can I access its value in my ViewController.swift?
现在如何在我的 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".
我 ctrl+drag 文本字段到我的 ViewController.swift 文件中。然后在弹出框中选择“outlet”并将其命名为“myInput”。
Then in another function, I access its value by using self.myInput.text
.
然后在另一个函数中,我使用self.myInput.text
.
Is this the only way to access its input? Is my approach following Swift conventions?
这是访问其输入的唯一方法吗?我的方法是否遵循 Swift 约定?
采纳答案by Hayley Guillou
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.
是的,您IBOutlet
从故事板创建一个并使用它进行引用的方法self.myInput.text
是在 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.
至于是否使用self.myInput
vs. myInput
,我更喜欢一直写,self
因为很明显变量是一个属性,很可能会在很多不同的地方发生变化(与局部变量相反)。此外,一旦你在self
那里,你就不必担心引入具有相同名称的本地变量或进行更改,如果你将代码块复制并粘贴到需要 self.