Joe Joe - 2 months ago 10
Swift Question

Detect and Remove blank tableViewCell in Swift

I have two tableView running in my project.I have successfully passed data between two tableView and saved it as a tableView array into my second tableView using segue.I have another function to connect my second tableview using tabBar button. Everytime, when I press the tabBar button it creates a blank tableViewCell at indexPath:0. I can understand why is happening but I am not sure how to stop. My code below

AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

let defaultValues = ["NewArray": [String]()]
UserDefaults.standard.register(defaults: defaultValues)

return true
}


MY Second VC

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let defaults = UserDefaults.standard
newArray = defaults.array(forKey: "NewArray") as! [String]
// newArray.append(newItem)
newArray.insert(newItem, at: 0)
defaults.set(newArray, forKey: "NewArray")
self.favTableView?.reloadData()
}


Thanks in Advance...

Answer

Actually the easiest solution is to check if newItem is not empty, because if the view is presented from the segue a (non-empty) string is passed to the newItem property.

override func viewDidLoad() {
  super.viewDidLoad()

  let defaults = UserDefaults.standard
  newArray = defaults.array(forKey: "NewArray") as! [String]
  // newArray.append(newItem)
  if !newItem.isEmpty {
    newArray.insert(newItem, at: 0)
    defaults.set(newArray, forKey: "NewArray")
  }
  self.favTableView?.reloadData()
}
Comments