[英]Adding UITextField outside ViewdidLoad
我似乎無法弄清楚如何在viewdidload方法之外添加TextField
。
我有一個function
,用於檢查某個選擇(在UIPickerView
)是否為歐洲,如果是,它需要添加一個新的TextField
,如果不是(並且該TextField
存在),則應將其刪除。
這是我的代碼:
func updateLabel(){
switch country{
case "Internationaal":
tailleSize = taille.international
case "Europe":
var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 40.00));
myTextField.backgroundColor = UIColor.grayColor();
myTextField.placeholder=" Enter here";
//myTextField.text = " Enter here";
myTextField.borderStyle = UITextBorderStyle.Line;
myTextField.secureTextEntry=true;
tailleSize = String(taille.europe)
default:
tailleSize = String(taille.europe)
}
}
每當用戶按下button
或從UIPickerView
選擇一項時,都會運行updateLabel
。
我怎樣才能做到這一點?
我試圖在變量中獲取主viewcontroller並將其添加到那里,但這是失敗的。
我認為定義您的UITextField單獨將其添加到hidden
在viewDidLoad
上的視圖中會更有意義,這將使switch語句更整潔,並且您的textfield可以重復使用,而不是每次都重新創建。
視圖控制器
override func viewDidLoad() {
super.viewDidLoad()
addTextFieldToView()
}
var myTextField:UITextField!
func addTextFieldToView() {
myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 40.00))
myTextField.backgroundColor = UIColor.grayColor()
myTextField.placeholder = "Enter here"
myTextField.borderStyle = UITextBorderStyle.Line
myTextField.secureTextEntry = true
myTextField.hidden = true
self.view.addSubview(myTextField)
}
func updateLabel(){
switch country{
case "International":
tailleSize = taille.international
myTextField.hidden = true
case "Europe":
tailleSize = String(taille.europe)
myTextField.hidden = false
default:
tailleSize = String(taille.europe)
myTextField.hidden = true
}
}
您也可以利用enabled
屬性來啟用和禁用文本字段,而不是使其不可見。 myTextField.enabled = false
以“常規”方式將TextField添加到您的Storyboard中所需的位置,並將其與代碼連接。
override func viewDidLoad() {
super.viewDidLoad()
myTextField.hidden = true; //TextField disappears
//You also can set the textField in Interface Builder to hidden.
}
func updateLabel(){
switch country{
case "Internationaal":
tailleSize = taille.international
case "Europe":
myTextField.hidden = false; //TextField appears
myTextField.backgroundColor = UIColor.grayColor();
myTextField.placeholder=" Enter here";
//myTextField.text = " Enter here";
myTextField.borderStyle = UITextBorderStyle.Line;
myTextField.secureTextEntry=true;
tailleSize = String(taille.europe)
default:
tailleSize = String(taille.europe)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.