UIKit框架-高级控件:6.UIPickerView与UIImageView结合使用

来源:互联网 发布:淘宝红包雨从哪里找 编辑:程序博客网 时间:2024/06/05 19:11

在前面, 我们用UIPickerView,UILabel, UITextFeild做了一个日期选择的小Demo, 现在让我们继续来看看UIPickerView和其他UI控件的结合.


1.定义全局变量

@interface ViewController (){    UILabel *_label;    UIImageView *_imageView;}@end



2.在.h文件里遵守代理方法

#import <UIKit/UIKit.h>@interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>@end


3.添加UILabel

- (void)myLabel{    _label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 45, 20)];    [_label setBackgroundColor:[UIColor greenColor]];    [_label setText:@"头像: "];    [self.view addSubview:_label];}


4.添加UIImageView

#pragma mark - UIImageView方法- (void)myImageView{    CGFloat imageViewX = _label.frame.size.width + 30;    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageViewX, 28, 200, 200)];    [_imageView setBackgroundColor:[UIColor redColor]];    [self.view addSubview:_imageView];}


5.添加UIButton

- (void)myButton{    CGFloat buttonX = _label.frame.size.width + 30;    CGFloat buutonY = _imageView.frame.size.height + 40;    CGFloat buttonW = _imageView.frame.size.width;        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];    [button setFrame:CGRectMake(buttonX, buutonY, buttonW, 30)];    [button setTitle:@"选择头像按钮" forState:UIControlStateNormal];        [button setBackgroundColor:[UIColor blackColor]];    [button addTarget:self action:@selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:button];}



6.添加UIButton的监听方法

- (void)selectPhoto{    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];    [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];    [imagePickerController setAllowsEditing:YES];    [imagePickerController setDelegate:self];    [self presentViewController:imagePickerController animated:YES completion:nil];}


7.添加ImagePikerController的代理方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{    NSLog(@"%@", info);    UIImage *image = info[@"UIImagePickerControllerEditedImage"];    [_imageView setImage:image];    [self dismissViewControllerAnimated:YES completion:nil];}

PS: UIImagePickerControllerEditedImage这个东西是在info里面打印出来的, 而info就是一个Dictionary, 里面有几个键值对, 例子中选择的是可以截取一部分图像添加到UIImageView中.



8.在viewDidLoad中实现所有的方法

- (void)viewDidLoad {    [super viewDidLoad];    [self myLabel];    [self myImageView];    [self myButton];}




最终的效果是:

  

 

 

PS: 腾讯QQ里面选择头像也是这么做的.





好了, 这次我们就讲到这里, 下次我们继续~~~

0 0
原创粉丝点击