2015-06-21 39 views
0

我有一個具有標籤以及文本字段的自定義UITableViewCell的UITableView安裝程序。每當現在我改變文本字段的文本時,隨機的其他單元的文本字段中的文本也會改變。UITableView更改一個單元格中的文本,以及其他更改中的文本

public class ChangePriceTableViewCell: UITableViewCell { 

    @IBOutlet weak var priceField: UITextField! 
    @IBOutlet weak var productName: UILabel! 
    @IBAction func changePrice(sender: UITextField) { 
     println(sender.text) 
    } 

    public override func layoutSubviews(){ 

     var toolbar = UIToolbar.new() 
     toolbar.frame.size.height = 35 

     var doneButton:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "hideKeyboard") 

     var space:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) 

     var items = [AnyObject]() 
     items.append(space) 
     items.append(doneButton) 

     toolbar.items = items 

     priceField.inputAccessoryView = toolbar 
    } 

    public func configure(product: String) { 
     self.productName.text = product 


    } 

    func hideKeyboard() { 
     println("Test") 
     priceField.resignFirstResponder() 
    } 


} 

和數據源:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 12//self.products.keys.count 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     //println(self.products[self.products.keys[section]]) 
     return 2//self.products[self.products.keys[section]]!.count 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     var cell = tableView.dequeueReusableCellWithIdentifier("change") as! ChangePriceTableViewCell 

     //var prods = self.products[self.products.keys[indexPath.section]] 
     //var productName = prods?[indexPath.row] as! String 
     //cell.configure(productName) 

      cell.configure("Test") 
     return cell 
    } 

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return "Test"//self.products.keys[section].uppercaseString 
    } 

從而改變始終是屏幕外的細胞。有時甚至在兩個單元之間跳轉!

回答

2

你是單元格被重用。請在ChangePriceTableViewCell中實現此方法:

func prepareForReuse() // if the cell is reusable (has a reuse identifier), this is called just before the cell is returned from the table view method dequeueReusableCellWithIdentifier:. If you override, you MUST call super. 

並將正確的默認值設置爲單元格。