ios 实现拍照与显示在界面上

1、添加权限与描述

2、代码

objectivec 复制代码
#import "ViewController.h"

@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建显示照片的imageView
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 200, 200)];
    [self.view addSubview:self.imageView];
    
    // 创建拍照按钮
    UIButton *takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [takePhotoButton setTitle:@"拍照" forState:UIControlStateNormal];
    takePhotoButton.frame = CGRectMake(50, 350, 100, 50);
    [takePhotoButton addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:takePhotoButton];
}

- (void)takePhoto {
    // 检查相机是否可用
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"相机不可用" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    // 创建 UIImagePickerController
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

// 拍照完成后调用的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
    self.imageView.image = selectedImage;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 用户取消拍照时调用的代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
相关推荐
CocoaKier3 小时前
苹果开发者注意,请在2027年1月31日前完成合规验证,否则中国区可能下架
ios·aigc·apple
二流小码农8 小时前
鸿蒙开发:证书只能创建3个,第4个应用怎么办
android·ios·harmonyos
bcbnb8 小时前
Windows 上 iOS 开发接 CI,KXBuild 自托管 runner 出签名 ipa
后端·ios
CodeClimb13 小时前
Mac 磁盘无法推出(DMG外接盘)排查处理教程
macos
疯华整猫14 小时前
别再抄 Flutter 了:2026 年 Android / iOS / 小程序跨端架构选型的四本成本账
android·前端·ios
黑科技iOS上架14 小时前
iOS游戏换皮上架困境:4.3同质化拒审
人工智能·ios·审核
黑科技iOS上架14 小时前
iOS二次开发应用上架难题:4.3a同质化拒审
ios·审核
传奇开心果编程14 小时前
【Flutter踩坑排雷】第30课:异常未捕获坑|未捕获异常直接闪退,全局兜底故障处理
android·flutter·ios·移动开发·dart·ui框架·声明式ui
茶底世界之下15 小时前
海边游乐场的黄昏:用 Awaking 留住一层暖光
ios·app·产品
90后的晨仔1 天前
Xcode 27.1 下,老工程如何在 iPhone Duo 模拟器上跑起来
ios