*我想在每次按下添加按钮时插入新行(条件:输入有效的电子邮件地址)。 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._%+-]+@[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,但它无效。
答案 0 :(得分:0)
您应该将isValidEmail()和addEmailButton()移动到此控制器中的ViewController和控制表视图。