-1
*每次按下添加按鈕(條件:輸入有效的電子郵件地址)時,我想插入新行。 enter image description here 這裏是我的代碼:如何在桌面視圖中按下單元格按鈕時創建新單元格
import UIKit
var totalCells=0
class AddEmailTableCell: UITableViewCell,UITextFieldDelegate {
var obj:UIViewController=ViewController()
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var addEmailLabel: UILabel!
@IBOutlet weak var addEmailImg: UIImageView!
func isValidEmail(testStr:String) -> Bool {
// print("validate calendar: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
addButton.isHidden=true
self.textField.delegate=self
}
@IBAction func addEmailButton(_ sender: Any) {
if(textField.text == nil || (textField.text?.isEmpty)!) {
print("email not filled")
return
}
if (isValidEmail(testStr: textField.text!)==false){
print("email not valid")
return
}
totalCells=totalCells+1
let index=IndexPath(row: totalCells, section: 0)
(obj as! ViewController).tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)
print(totalCells)
print("valid")
}
}
我的viewController代碼在這裏給出:
import UIKit
class ViewController:
UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if totalCells==0{
return 1
}
return totalCells
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell=tableView.dequeueReusableCell(withIdentifier: "addEmail", for: indexPath) as! AddEmailTableCell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
所以我應該怎麼辦在這裏,我呼籲tableview.reloadData並通過細胞的更新數我的tableview,但它不工作。
在'ViewController'中需要一個**模型**(一個數據源數組),並且您應該將**控件*相關邏輯從**視圖**(單元格)移動到**控制器**。 – vadian