我尝试使用自定义方法(由其他用户创建),该方法复制我创建的名为[Ingredient]的结构的实例。方法是这样的;
convenience init(copyingIngredientsFrom meal: Meal, atIndexPaths indexPaths: [IndexPath]) {
let sections = meal.ingredientSections
self.init(mealTitle: selectedMeal!.mealTitle, mealID: selectedMeal!.mealID, mealImage: selectedMeal!.mealImage, ingredients: indexPaths.map {sections[$0.section][$0.row]})
初始餐初始是;
init(mealTitle: String, mealID: Int, mealImage: UIImage?, ingredients: [Ingredient]) {
self.mealTitle = mealTitle
self.mealID = mealID
self.mealImage = mealImage!
self.ingredients = [Ingredient]()
}
新餐的目的是创造一个新的[膳食]对象,复制所选择的成分。我在使用IndexPathsForSelectedRows时遇到了一些问题。我理想情况下也喜欢选择"选择"默认情况下,但这不是必需的。可以看出,此代码在segue之前执行。理想情况下,我想在修复代码后附加newMeal而不是SelectedMeal。这段代码的问题在于它当前崩溃了应用程序,如果选择了1和x之间的任何值,则indexPaths.count只会显示1并且仍会崩溃,但如果我没有选择任何值,则只打印一次,一旦我&#39 ;点击按钮。如果我删除if语句,那么应用程序正常工作没有问题。
if let list = detailTableViewIn.indexPathsForSelectedRows {
print(indexPaths.count)
let newMeal = Meal(copyingIngredientsFrom: selectedMeal!, atIndexPaths: list)
}
myMeals.insert(selectedMeal!, at: myMealsPosition)
myMealsPosition += 1
// Segues away
self.performSegue(withIdentifier: "MealCreated", sender: self)
非常感谢任何帮助。
答案 0 :(得分:0)
看一下这个例子:
let Meals = [Meal]
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("MealCreated", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath = self.tableView.indexPathForSelectedRow
let meal = Meals[indexPath!.row]
if segue.identifier == "MealCreated"{
let DetailMeal = (segue.destinationViewController as! DetailMealController)
DetailMeal.mealTitle = meal.mealTitle
DetailMeal.mealID = meal.mealID
DetailMeal.mealImage = meal.mealImage
DetailMeal.ingredients = meal.ingredients
}
}