2014-12-04 88 views
0

我正在基於用戶的偏好以編程方式添加一些UISteppers和UITextField。但是,我似乎無法獲得UIStepper觸摸點擊 - 它看起來沒有在 -/+按鈕上註冊觸摸。我試着將用戶交互的userTriggers UIView設置爲禁用,但那不起作用。無法與UIStepper進行交互

1)我還能嘗試什麼?

2)我還需要能夠增加相應的UITextField,然後將其寫入到我的UserData.plist文件中,並且我不確定如何訪問每個字段。我應該將它們添加到某種數組中嗎?

import UIKit 

class TriggersViewController: UIViewController{ 

@IBOutlet var userTriggers:UIView! 
@IBOutlet var saveButton:UIButton! 

var triggersList:Array<String>! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    loadTriggers() 
    var prevInput = 250; 
    for index in 0..<triggersList.count{ 

     //label for trigger 
     var label = UILabel(frame: CGRectMake(0, 0, 200, 21)) 
     label.center = CGPointMake(120, CGFloat(prevInput)) 
     label.textAlignment = NSTextAlignment.Left 
     label.text = triggersList[index] 
     userTriggers.addSubview(label) 

     //input box for trigger 
     var input = UITextField(frame: CGRectMake(0, 0, 50, 21)) 
     input.center = CGPointMake(250, CGFloat(prevInput)) 
     input.text = "0"; 
     //add input to triggersView 
     userTriggers.addSubview(input); 

     //UIStepper 
     var stepper = UIStepper(frame: CGRectMake(0, 0, 50, 21)) 
     stepper.center = CGPointMake(300, CGFloat(prevInput)) 
     stepper.addTarget(self, action: "stepperValueChanged:", forControlEvents: .ValueChanged) 
     stepper.enabled = true 
     //add stepper to triggersView 
     userTriggers.addSubview(stepper); 


     prevInput += 50 //increment for height 

    } 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func stepperValueChanged(sender:UIStepper!){ 
    println("It Works, Value is --&gt;\(Int(sender.value).description)") 
} 

func loadTriggers(){ 
    var myDict: NSDictionary? 

    if let path = NSBundle.mainBundle().pathForResource("UserConfigs", ofType: "plist") { 
     myDict = NSDictionary(contentsOfFile: path) 
    } 
    if let dict = myDict { 
     triggersList = dict["Triggers"] as Array<String> 
    } 
} 

}

回答

2

你確實需要設置在上海華用戶交互功能。在這裏看到更多的信息:UIView -- "user interaction enabled" false on parent but true on child?

此外,第二個問題是一個簡單的(但不是很理想)的方式來訪問每個字段是使用標籤。 Clean-ish的方式是使用枚舉定義標籤。然後使用viewWithTag訪問字段。

但是,有比標籤更好的方法(例如,因爲任何視圖都可以被賦予任何標籤,所以它們不是非常防錯的)。如果只有幾個文本字段/步進器,儘管您可以輕鬆地爲每個視圖控制器添加屬性。最好的解決方案是將步進器和字段組合在UIView子類中(假設它們彼此相鄰),並將對這些分組的引用存儲在視圖控制器中(可能位於數組中)。

+0

哦,我正要給+1,直到我閱讀'viewWithTag'位。屬性是首選。如果這不是理想的(也許有很多),那麼總比使用'標籤'更好。 – Fogmeister 2014-12-04 21:32:21

+0

Sheesh,很好,答案已更新。怎麼樣 ? – shim 2014-12-04 21:44:55

+1

不需要「sheesh」。我真的認爲'tag'應該完全從'UIView'中移除。它促進了不好的模式。現在好多了。 +1 – Fogmeister 2014-12-04 21:55:36