#ios #iphone #objective-c #uitableview #uiimageview
#iOS #iPhone #objective-c #uitableview #uiimageview
Вопрос:
я уже передал входной текст с помощью prepareForSegue, текст в mutablearray, затем передал этот массив с помощью prepareforeSegue во второй VC с помощью tableview, чтобы ячейка таблицы теперь отображала имя. Но что с выбранным / выбранным изображением в UIImageView в первом vc, чтобы ячейка таблицы во втором VC могла отображать изображение в строке рядом с именем? мне удается сделать это с помощью image из imagexxassets я следовал той же логике, что и передача текста, но продолжаю терпеть неудачу.
ViewController.h
#import <UIKit/UIKit.h>
#import "TableViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface ViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (strong, nonatomic) IBOutlet UITextField *inputName;
@property (nonatomic) NSMutableArray *items;
//@property (nonatomic) NSMutableArray *images;
- (IBAction)AddData:(id)sender;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) IBOutlet UIButton *selectPhoto;
@property (strong, nonatomic) IBOutlet UIButton *takePhotoFromCamera;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_items = [[NSMutableArray alloc]init];
//_images = [[NSMutableArray alloc]init];
[self.takePhotoFromCamera addTarget:self action:@selector(_takePhoto) forControlEvents:UIControlEventTouchUpInside];
[self.selectPhoto addTarget:self action:@selector(_selectPhoto) forControlEvents:UIControlEventTouchUpInside];}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)AddData:(id)sender
{
//[_images addObject:self.imageView.image];
//[_images insertObject:self.imageView.image atIndex:0];
if ([self.inputName.text length]> 0)
{
[_items addObject:self.inputName.text];
//[_images addObject:self.imageView.image];
[self performSegueWithIdentifier:@"tableSegue" sender:self];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Error"
message:@"You must enter some data"
delegate:self
cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
}
}
- (void)addItemViewController:(TableViewController *)controller didFinishSelectingItem:(NSMutableArray *)item selectedTag:(int)tag{
NSLog(@"DATA=%@", item);
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"tableSegue"])
{
TableViewController *controller = (TableViewController *)segue.destinationViewController;
controller.items = _items;
//TableViewController *controller1 = (TableViewController *)segue.destinationViewController;
//controller1.images = _images;
NSLog(@"%@",self.inputName.text);
self.inputName.text = NULL;
}
}
#pragma mark code for images
-(void)_takePhoto
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)_selectPhoto
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:NO completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
}
}
-(void)imagePickerControllerDidCancel:
(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
TableViewController.h
#import <UIKit/UIKit.h>
//using delegate
@protocol TableViewControllerDelegate <NSObject>
- (void)addItemViewController:(id)controller didFinishSelectingItem:(NSMutableArray *)item selectedTag:(int)tag;
@end
//extra attention here
@interface TableViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
// id of delegate
@property (nonatomic, weak) id <TableViewControllerDelegate> delegate;
@property (nonatomic) NSMutableArray *items;
//@property (nonatomic) NSMutableArray *images;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@end
TableViewController.m
#import "TableViewController.h"
@interface TableViewController ()
@end
@implementation TableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// code for reversing objects in array so tableview can put new rows on top
//_items = [[[_items reverseObjectEnumerator] allObjects] mutableCopy];
self.tableView.delegate = self;
self.tableView.dataSource = self;
// setting invisible footer to display only rows which contains data and to remove border lines in tableview
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 10.0f)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:@"BasicCell" forIndexPath:indexPath];
//NSString *lijevaSlika = [NSString stringWithFormat:@"dice%i", sum];
//[questionTexts objectAtIndex:0]
//NSString *selectedImage = [NSString stringWithFormat:_images];
myCell.imageView.image = [UIImage imageNamed:@"2.png"];
myCell.textLabel.text = _items[indexPath.row]; //name of objects in array are displayed in cells
myCell.textLabel.textColor = [UIColor blueColor]; //changing color of text in cell
//changing background of cell
/*myCell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back.png"]];
myCell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"front.png"]];
*/
return myCell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.items count]; //objects in arrays - rows in table
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[_items removeObjectAtIndex:indexPath.row]; //swipe to left do delete row
[self.tableView reloadData];
}
/*- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//selected row returns to previous viewcontroller
[self.navigationController popViewControllerAnimated:YES];
}
*/
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
Ответ №1:
Сначала вам нужно сохранить выбранные изображения в массиве, затем вы должны передать этот массив так же, как вы передаете _items
массив.Затем в cellForRowAtIndexPath
of TableViewController
добавьте эту строку и проверьте, получаете ли вы что-либо в _images
массиве
myCell.imageView.image = [_images objectAtIndex:indexPath.row];
Комментарии:
1. боже, большое вам спасибо, я перепробовал myCell.ImageView.image = [UIImage imageNamed:_images»]; и получил ошибки, я использовал ваш код, и теперь он работает, я не могу вас отблагодарить 🙂
2. вы видите код для uialertview в VC.m, в нем говорится, что если текстовое поле пустое, отображается uialert view, как сделать то же самое, если изображение не выбрано. например, если UIImageView не выполняет uialertview, попробует
3. спасибо, я разрешил это с помощью if ([self.inputName.длина текста]> 0 amp;amp; ImageView.image ! = nil)