iOS 在表格视图中插入第二个元素



我有一个文本字段,当用户点击它时,会出现一个带有国家货币列表的 table1,然后用户选择一种货币并将其添加到 table2,我可以添加一种货币,当我将另一种货币添加到 table2 时,应用程序崩溃并显示以下错误:由于未捕获的异常"NSInternalInconsistencyException"而终止应用程序, 原因:"在无效的索引路径处请求 rect({长度 = 2,路径 = 0 - 1}(">

class CurrencySecondStep: UIViewController ,UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate {
@IBOutlet weak var tableViewAddedByUser: UITableView!
@IBOutlet weak var amountToBeExchanged: UILabel!
@IBOutlet weak var tableViewFor: UITableView!
@IBOutlet weak var textFieldFor: UITextField!

//cell identifier
let cellReuseIdentifier = "cell"
//struct
struct Currency {
var country = String()
var currencyCode = String()
var currencyFlag = UIImage()
}

var addedCurrencyByUserArray = [Currency]()
var currencyArr = [
Currency(country: "United Arab Emirates Dirham", currencyCode: "AED",currencyFlag: UIImage(named:"United-Arab-Emirates")!),
Currency(country: "US Dollar", currencyCode: "USD",currencyFlag: UIImage(named:"United-States")!),
Currency(country: "Afghan Afghani (1927–2002)", currencyCode: "AFA",currencyFlag: UIImage(named:"Afghanistan")!),
Currency(country: "Albania Lek", currencyCode: "ALL",currencyFlag: UIImage(named:"Albania")!),
Currency(country: "Algerian Dinar", currencyCode: "DZD",currencyFlag: UIImage(named:"Algeria")!),
Currency(country: "Angolan Kwanza", currencyCode: "AOA",currencyFlag: UIImage(named:"Angola")!),
Currency(country: "Argentine Peso", currencyCode: "ARS",currencyFlag: UIImage(named:"Argentina")!),
Currency(country: "Armenian Dram", currencyCode: "AMD",currencyFlag: UIImage(named:"Armenia")!)

]
//searched results
var filteredCurrenciesOffer = [Currency]()
//currency code to be sent to google finance
var currencyCodeOffer = ""
var currencyPassed = ""
var countryChoice = ""
var countryCodeChoice = ""
var countryflagChoice = UIImage()



@IBAction func textFieldChanged(_ sender: AnyObject) {
tableViewFor.isHidden = true
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableViewFor.delegate = self
tableViewFor.dataSource = self
tableViewFor.isHidden = true
textFieldFor.delegate = self
textFieldFor.addTarget(self, action: #selector(textFieldActive), for: UIControlEvents.touchDown)
textFieldFor.addTarget(self, action:#selector(textFieldDidChange) , for: UIControlEvents.editingChanged)
//hide or show keyboard
textFieldFor.addTarget(self, action: #selector(textFieldShouldReturn), for: UIControlEvents.touchDown)
amountToBeExchanged.text = currencyPassed

//table added By User
tableViewAddedByUser.delegate = self
tableViewAddedByUser.dataSource = self
tableViewAddedByUser.isHidden = true
}

当用户按添加按钮插入第二个元素时,应用崩溃

@IBAction func addPressed(_ sender: Any) {
if(textFieldFor.text == ""){
displayError(title: "Currency Type",message:"Please Pick Your Currency")

}else{
tableViewAddedByUser.isHidden = false
addedCurrencyByUserArray.append(Currency(country: countryChoice, currencyCode: countryCodeChoice,currencyFlag: countryflagChoice))
tableViewAddedByUser.beginUpdates()
let insert = IndexPath(row: addedCurrencyByUserArray.count - 1, section: 0)
tableViewAddedByUser.insertRows(at: [insert], with: .automatic)
tableViewAddedByUser.endUpdates()




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

func textFieldDidEndEditing(_ textField: UITextField) {

filteredCurrenciesOffer = currencyArr.filter { currencyGiven in
return currencyGiven.country.lowercased().contains(textFieldFor.text!.lowercased())
}
//reload table based on the user pick
tableViewFor.reloadData()

}
func textFieldDidChange(textField: UITextField) {

//update search based on user search
filteredCurrenciesOffer = currencyArr.filter { currencyGiven in
return currencyGiven.country.lowercased().contains(textFieldFor.text!.lowercased())
}
tableViewFor.reloadData()
}
// Toggle the tableView visibility when click on textField
func textFieldActive(textField: UITextField) {

tableViewFor.isHidden = !tableViewFor.isHidden

}


//hide keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

// MARK: TableView Functions

func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int?
if (tableView == self.tableViewFor && textFieldFor.text != ""){
count = filteredCurrenciesOffer.count
}else if(tableView == self.tableViewFor && textFieldFor.text == ""){
count = currencyArr.count
}
if(tableView == self.tableViewAddedByUser){
count = addedCurrencyByUserArray.count
print("number of rows")
print(count!)
}

return count!

}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableViewFor.dequeueReusableCell(withIdentifier: "cell", for: indexPath)      as! CustomCell

var currency: Currency
if (tableView == self.tableViewFor){
if  ( textFieldFor.text != "") {

currency = filteredCurrenciesOffer[indexPath.row]
} else {
currency = currencyArr[indexPath.row]
}

cell.flag.image = currency.currencyFlag
cell.country.text = currency.country
cell.currencyCode.text = currency.currencyCode

}
if (tableView == self.tableViewAddedByUser){
currency = addedCurrencyByUserArray[indexPath.row]

cell.flag.image = currency.currencyFlag
cell.country.text = currency.country
cell.currencyCode.text = currency.currencyCode

}

return cell
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

var currency: Currency

if(tableView == tableViewFor){

if  textFieldFor.text != "" {
currency = filteredCurrenciesOffer[indexPath.row]
} else {
currency = currencyArr[indexPath.row]
}

//add image to currency text field
let leftImageView = UIImageView()
leftImageView.image = currency.currencyFlag
let leftView = UIView()
leftView.addSubview(leftImageView)
leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
textFieldFor.leftViewMode = .always
textFieldFor.leftView = leftView
//add country to currency text field
textFieldFor.text = currency.country
countryChoice = currency.country
countryCodeChoice = currency.currencyCode
countryflagChoice = currency.currencyFlag
currencyCodeOffer = currency.currencyCode
tableViewFor.isHidden = true
textFieldFor.endEditing(true)

}



}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0
}

//hide the table and keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
guard let touch:UITouch = touches.first else
{
return;
}
if touch.view != tableViewFor
{
textFieldFor.endEditing(true)
tableViewFor.isHidden = true
}
}

func displayError(title:String,message:String){
// Create the alert controller
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
// Create the actions
let retryButton = UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(retryButton) 
}

}

我认为问题发生在您的

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

在第一行,您始终将单元格从tableViewFor中取消排队,即使您需要一个用于tableViewAddedByUser的单元格。

尝试用这个替换第一行,这将从参数中发送的 tableView 中取消单元格的排队:

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

如果这不起作用,请尝试不指定 indexPath,如下所示:

let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell

最新更新