尝试使用轻击手势创建图像选择器,因此当点击默认图片时,它允许用户从设备的图片库中选择图像。出于某种原因,当我在iOS模拟器中单击视图时,它根本什么都没做,而且我也不知道为什么。
这是我到目前为止所拥有的。我对Objective-C很陌生
ViewController.m:
#import "ViewController.h"
interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *brandField;
@property (weak, nonatomic) IBOutlet UITextField *priceField;
@property (weak, nonatomic) IBOutlet UITextField *additionalNotesField;
@property (weak, nonatomic) IBOutlet UIButton *addItem;
@property (weak, nonatomic) IBOutlet UIButton *cancelAdditem;
@property (weak, nonatomic) IBOutlet UIImageView *toyImage;
- (IBAction)imageSelect:(UITapGestureRecognizer *)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_nameField.delegate = self;
_brandField.delegate = self;
_priceField.delegate = self;
_additionalNotesField.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL) textFieldShouldReturn:(UITextField *) textField {
textField.resignFirstResponder;
return true;
}
-(void) textFieldDidEndEditing:( UITextField *) textField {
_nameField.text = textField.text;
_brandField.text = textField.text;
_priceField.text = textField.text;
_additionalNotesField.text = textField.text;
}
- (IBAction)imageSelect:(UITapGestureRecognizer *)sender {
// Hide the keyboard
_nameField.resignFirstResponder;
_brandField.resignFirstResponder;
_priceField.resignFirstResponder;
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init]; // Creates image picker
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // Source for picker is saved photos. Only allow photos to be picked, not taken
// Make sure the picker is notified when the user picks an image
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:true completion:nil];
}
// UIImagePickerControllerDelegete
-(void) imagePickerDidCancel:(UIImagePickerController *) imagePicker {
[self dismissViewControllerAnimated:true completion:nil]; // Dimiss the picker if the user canceled
}
-(void) imagePicker:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage* selectedImage = info[UIImagePickerControllerOriginalImage];
_toyImage.image = selectedImage; // Set the image view to display the selected image
// Dimiss the picker
[self dismissViewControllerAnimated:true completion:nil];
}
@end
答案 0 :(得分:0)
正如Larme所说,我需要添加以下行:
_toyImage.userInteractionEnabled = YES;