iOS swift - 在 TableView 中插入第二个元素

标签 ios swift tableview

我有一个文本字段,当用户点击它时,会出现一个表1,其中包含国家/地区货币列表,然后用户选择一种货币并将其添加到表2中,我可以添加一种货币,当我将另一种货币添加到表2中时应用程序崩溃并出现以下错误:由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“在无效索引路径处请求矩形 ({length = 2, path = 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)

在第一行,即使您需要 tableViewAddedByUser 的单元格,您也始终将单元格从 tableViewFor 中出列。

尝试用此替换第一行,这将使参数中发送的 tableView 中的单元格出队:

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

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

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

关于iOS swift - 在 TableView 中插入第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038809/

相关文章:

ios - 如果用户强制退出,iOS 是否会将我的应用程序启动到后台?

ios - WKWebView 中的奇怪边距

ios - 当我在真实设备中频繁推送/返回 View Controller 时出现错误 "Index out of range"- Swift

ios - Swift: NSArrayM controllerWillChangeContent:]: 无法识别的选择器发送到实例

swift - 使用 NSUSerDefaults 保存 Swift TableView 数据

Swift 尝试为同一索引路径使多个单元格出队,这是不允许的

ios - 如何判断Plot已经被Core-Plot渲染过

IOS:应用程序进入后台后检测锁定?

ios - 如何在 iOS 上更改*只是*按钮的填充

ios - 隐藏 subview 会在 View 上留下微弱的阴影