[英]How to go to another view controller when button is pressed in swift 3
[英]how to set a relationship after save button is pressed in another view controller?
我在代碼中設置關系時遇到麻煩。
當按下“將食物添加到列表”上的保存按鈕時,我想將該食物的關系設置為“保持”,通過添加食物的列表進行。 我現在在AddFoodToListTVC中擁有的內容:
- (IBAction)save:(id)sender
{
Food *food = [NSEntityDescription insertNewObjectForEntityForName:@"Food"
food.name = foodToListNameTextField.text;
[food setHeldBy:?????];
用外行的話來說,我想說的是“這種食物被我們剛才所看的清單所占據”。
這是我的第一個iOS項目,很抱歉遇到新手。 提前致謝!
好的,我不知道如何使用情節提要,但如果您願意接受此類答案,我也知道如何使用純代碼執行類似的操作。
對於簡單的表視圖,您需要遵循兩個通用規則:
1)告訴表格需要顯示多少行
2)告訴表格您需要在每個單元格中呈現哪些元素
表中的行數通常由View Controller的.h文件中聲明的數組中的元素數定義。
就像是
// View Controller header file (.h file)
@interface
{
...
NSMutableArray *arrOfItems;
}
然后在實現文件中,將食物添加到數組中,保存Core Data上下文,然后從Core Data中執行獲取並將結果存儲到類變量數組中:
// this method gets called when your button is pressed
-(void)addFoodToList
{
Food *food = [NSEntityDescription insertNewObjectForEntityForName:@"Food"
food.name = foodToListNameTextField.text;
[managedObjectContext save:nil];
// for simplicity sake, we're doing a simple table reload
[self fetchData]; // see below
[myTableView reloadData]; // reloads the table to include the newly added food
}
-(void)fetchData
{
// core data fetch request of all items we want to display in the list
arrOfItems = [managedObjectContext executeFetchRequest:request .... ];
}
注意,您應該在此表視圖委托方法中返回類變量數組中的項目數:
// View Controller implementation file (.m file)
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(int)section
{
// after adding the item to your arrOfItems and then doing a fetch request
// earlier (see above code), this next statement would return the correct value
return [arrOfItems count];
}
剩下要做的就是在UITableViewCellForRow方法中:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString cellID = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithID:cellID];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithTableViewCellStyle:UITableViewCellStyleDefault reusableIdentifier:cellID] autorelease];
// init your element foodItemLabel
foodTitleLabel = [[UILabel alloc] initWithFrame:...];
foodTitleLabel.tag = 1;
[cell.contentView addSubview:foodTitleLabel];
[foodTitleLabel release];
}
foodTitleLabel = (UILabel *)[cell.contentView viewWithTag:1];
FoodItem *foodItem = (FoodItem *)[arrOfItems objectAtIndexPath:indexPath.row];
// display the food name
foodTitleLabel.text = foodItem.title;
return cell;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.