iOS 圖片選擇器(仿微信)

HarveyDMIJ 7年前發布 | 16K 次閱讀 iOS開發 移動開發

照片選擇器是APP開發中經常使用的功能.比如對商品的評價,某些報告提交等都會用到.

你只要繼承我demo的HWPublishBaseController就可以了.在下面有說明.我在demo設置的是最多上傳9張照片,你可以自己根據需求修改,在工程中搜索

#define kMaxImageCount 9

這是我在項目中的使用,如圖:

 

 

 

不廢話,直接上代碼.其中用了第三方的東西.我demo中的EvaluateViewController頁是寫功能的主要看這個頁面就可以.它如上面所說就是繼承的HWPublishBaseController.demo中的代碼說明的很詳細可以參照此樣式自定義頁面.先說一說Base頁面.

這是Base頁面,你可以新建一個頁面繼承它,然后自定義頁面樣式.其中你可以根據需求是要大圖的數據信息還是縮放的小圖信息.這是小圖的://方形壓縮圖image 數組 @property(nonatomic,strong) NSMutableArray imageArray;這是大圖的- (NSArray )getBigImageArray;上傳圖片就要根據需求了,網上有很多.

首先是.h文件

//
//  HWPublishBaseController.h
//  PhotoSelector
//
//  Created by 洪雯 on 2017/1/12.
//  Copyright ? 2017年 洪雯. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "HWCollectionViewCell.h"
#import "JJPhotoManeger.h"
#import "HWImagePickerSheet.h"

@protocol HWPublishBaseViewDelegate <NSObject>

@optional

@end

@interface HWPublishBaseController : UIViewController

@property (nonatomic, assign) id<HWPublishBaseViewDelegate> delegate;

@property (nonatomic, strong) UICollectionView *pickerCollectionView;

@property (nonatomic, assign) CGFloat collectionFrameY;

//選擇的圖片數據
@property(nonatomic,strong) NSMutableArray *arrSelected;

//方形壓縮圖image 數組
@property(nonatomic,strong) NSMutableArray * imageArray;

//大圖image 數組
@property(nonatomic,strong) NSMutableArray * bigImageArray;

//大圖image 二進制
@property(nonatomic,strong) NSMutableArray * bigImgDataArray;

//圖片選擇器
@property(nonatomic,strong) UIViewController *showActionSheetViewController;

//collectionView所在view
@property(nonatomic,strong) UIView *showInView;

//圖片總數量限制
@property(nonatomic,assign) NSInteger maxCount;


//初始化collectionView
- (void)initPickerView;
//修改collectionView的位置
- (void)updatePickerViewFrameY:(CGFloat)Y;
//獲得collectionView 的 Frame
- (CGRect)getPickerViewFrame;

//獲取選中的所有圖片信息
- (NSArray*)getSmallImageArray;
- (NSArray*)getBigImageArray;
- (NSArray*)getALAssetArray;

- (void)pickerViewFrameChanged;

@end

這是.m文件 在新建頁面調用 [self initPickerView];這個方法是 初始化collectionView 然后根據需求調用updatePickerViewFrameY這個方法這個是修改collectionView的位置即照片的顯示位置.

//
//  HWPublishBaseController.m
//  PhotoSelector
//
//  Created by 洪雯 on 2017/1/12.
//  Copyright ? 2017年 洪雯. All rights reserved.
//

#import "HWPublishBaseController.h"

@interface HWPublishBaseController ()<UICollectionViewDelegate,UICollectionViewDataSource,JJPhotoDelegate,HWImagePickerSheetDelegate>{
    NSString *pushImageName;
    //添加圖片提示
    UILabel *addImageStrLabel;
}

@property (nonatomic, strong) HWImagePickerSheet *imgPickerActionSheet;

@end

@implementation HWPublishBaseController

static NSString * const reuseIdentifier = @"HWCollectionViewCell";

-(instancetype)init{
    self = [super init];
    if (self) {
        if (!_showActionSheetViewController) {
            _showActionSheetViewController = self;
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

/** 初始化collectionView */
-(void)initPickerView{
    _showActionSheetViewController = self;

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.pickerCollectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    if (_showInView) {
        [_showInView addSubview:self.pickerCollectionView];
    }else{
        [self.view addSubview:self.pickerCollectionView];
    }

    self.pickerCollectionView.delegate=self;
    self.pickerCollectionView.dataSource=self;
    self.pickerCollectionView.backgroundColor = [UIColor whiteColor];

    if(_imageArray.count == 0)
    {
        _imageArray = [NSMutableArray array];
    }
    if(_bigImageArray.count == 0)
    {
        _bigImageArray = [NSMutableArray array];
    }
    pushImageName = @"plus.png";

    _pickerCollectionView.scrollEnabled = NO;

    //上傳圖片提示
    addImageStrLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 50, 70, 20)];
    addImageStrLabel.text = @"上傳圖片";
    addImageStrLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    [self.pickerCollectionView addSubview:addImageStrLabel];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imageArray.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    // Register nib file for the cell
    UINib *nib = [UINib nibWithNibName:@"HWCollectionViewCell" bundle: [NSBundle mainBundle]];
    [collectionView registerNib:nib forCellWithReuseIdentifier:@"HWCollectionViewCell"];
    // Set up the reuse identifier
    HWCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"HWCollectionViewCell" forIndexPath:indexPath];

    if (indexPath.row == _imageArray.count) {
        [cell.profilePhoto setImage:[UIImage imageNamed:pushImageName]];
        cell.closeButton.hidden = YES;

        //沒有任何圖片
        if (_imageArray.count == 0) {
            addImageStrLabel.hidden = NO;
        }
        else{
            addImageStrLabel.hidden = YES;
        }
    }
    else{
        [cell.profilePhoto setImage:_imageArray[indexPath.item]];
        cell.closeButton.hidden = NO;
    }
    [cell setBigImageViewWithImage:nil];
    cell.profilePhoto.tag = [indexPath item];

    //添加圖片cell點擊事件
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
    singleTap.numberOfTapsRequired = 1;
    cell.profilePhoto .userInteractionEnabled = YES;
    [cell.profilePhoto  addGestureRecognizer:singleTap];
    cell.closeButton.tag = [indexPath item];
    [cell.closeButton addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];

    [self changeCollectionViewHeight];
    return cell;
}
#pragma mark <UICollectionViewDelegate>
//定義每個UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(([UIScreen mainScreen].bounds.size.width-64) /4 ,([UIScreen mainScreen].bounds.size.width-64) /4);
}

//定義每個UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(20, 8, 20, 8);
}

#pragma mark - 圖片cell點擊事件
//點擊圖片看大圖
- (void) tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer{
    [self.view endEditing:YES];

    UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
    NSInteger index = tableGridImage.tag;

    if (index == (_imageArray.count)) {
        [self.view endEditing:YES];
        //添加新圖片
        [self addNewImg];
    }
    else{
        //點擊放大查看
        HWCollectionViewCell *cell = (HWCollectionViewCell*)[_pickerCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
        if (!cell.BigImageView || !cell.BigImageView.image) {

            [cell setBigImageViewWithImage:[self getBigIamgeWithALAsset:_arrSelected[index]]];
        }

        JJPhotoManeger *mg = [JJPhotoManeger maneger];
        mg.delegate = self;
        [mg showLocalPhotoViewer:@[cell.BigImageView] selecImageindex:0];
    }
}
- (UIImage*)getBigIamgeWithALAsset:(ALAsset*)set{
    //壓縮
    // 需傳入方向和縮放比例,否則方向和尺寸都不對
    UIImage *img = [UIImage imageWithCGImage:set.defaultRepresentation.fullResolutionImage
                                       scale:set.defaultRepresentation.scale
                                 orientation:(UIImageOrientation)set.defaultRepresentation.orientation];
    NSData *imageData = UIImageJPEGRepresentation(img, 0.5);
    [_bigImgDataArray addObject:imageData];

    return [UIImage imageWithData:imageData];
}
#pragma mark - 選擇圖片
- (void)addNewImg{
    if (!_imgPickerActionSheet) {
        _imgPickerActionSheet = [[HWImagePickerSheet alloc] init];
        _imgPickerActionSheet.delegate = self;
    }
    if (_arrSelected) {
        _imgPickerActionSheet.arrSelected = _arrSelected;
    }
    _imgPickerActionSheet.maxCount = _maxCount;
    [_imgPickerActionSheet showImgPickerActionSheetInView:_showActionSheetViewController];
}

#pragma mark - 刪除照片
- (void)deletePhoto:(UIButton *)sender{

    [_imageArray removeObjectAtIndex:sender.tag];
    [_arrSelected removeObjectAtIndex:sender.tag];


    [self.pickerCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:sender.tag inSection:0]]];

    for (NSInteger item = sender.tag; item <= _imageArray.count; item++) {
        HWCollectionViewCell *cell = (HWCollectionViewCell*)[self.pickerCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
        cell.closeButton.tag--;
        cell.profilePhoto.tag--;
    }

    [self changeCollectionViewHeight];
}

#pragma mark - 改變view,collectionView高度
- (void)changeCollectionViewHeight{

    if (_collectionFrameY) {
        _pickerCollectionView.frame = CGRectMake(0, _collectionFrameY, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0)* ((int)(_arrSelected.count)/4 +1)+20.0);
    }
    else{
        _pickerCollectionView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0)* ((int)(_arrSelected.count)/4 +1)+20.0);
    }
    [self pickerViewFrameChanged];

}
/**
 *  相冊完成選擇得到圖片
 */
-(void)getSelectImageWithALAssetArray:(NSArray *)ALAssetArray thumbnailImageArray:(NSArray *)thumbnailImgArray{
    //(ALAsset)類型 Array
    _arrSelected = [NSMutableArray arrayWithArray:ALAssetArray];
    //正方形縮略圖 Array
    _imageArray = [NSMutableArray arrayWithArray:thumbnailImgArray] ;

    [self.pickerCollectionView reloadData];
}
- (void)pickerViewFrameChanged{

}
- (void)updatePickerViewFrameY:(CGFloat)Y{

    _collectionFrameY = Y;
    _pickerCollectionView.frame = CGRectMake(0, Y, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0)* ((int)(_arrSelected.count)/4 +1)+20.0);
}

#pragma mark - 防止奔潰處理
-(void)photoViwerWilldealloc:(NSInteger)selecedImageViewIndex
{
    NSLog(@"最后一張觀看的圖片的index是:%zd",selecedImageViewIndex);
}

- (UIImage *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize {
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }

    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
}
//獲得大圖
- (NSArray*)getBigImageArrayWithALAssetArray:(NSArray*)ALAssetArray{
    _bigImgDataArray = [NSMutableArray array];
    NSMutableArray *bigImgArr = [NSMutableArray array];
    for (ALAsset *set in ALAssetArray) {
        [bigImgArr addObject:[self getBigIamgeWithALAsset:set]];
    }
    _bigImageArray = bigImgArr;
    return _bigImageArray;
}
#pragma mark - 獲得選中圖片各個尺寸
- (NSArray*)getALAssetArray{
    return _arrSelected;
}

- (NSArray*)getBigImageArray{

    return [self getBigImageArrayWithALAssetArray:_arrSelected];
}

- (NSArray*)getSmallImageArray{
    return _imageArray;
}

- (CGRect)getPickerViewFrame{
    return self.pickerCollectionView.frame;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#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

然后新建一個頁面,繼承base頁面

#import <UIKit/UIKit.h>
#import "HWPublishBaseController.h"

@interface EvaluateViewController : HWPublishBaseController

@end

在這個.m頁面自定義樣式.用到上面我說的 [self initPickerView]和updatePickerViewFrameY這兩個就基本完成樣式設計.

//
//  EvaluateViewController.m
//  PhotoSelector
//
//  Created by 洪雯 on 2017/1/12.
//  Copyright ? 2017年 洪雯. All rights reserved.
//

#import "EvaluateViewController.h"
#import "BRPlaceholderTextView.h"
#import "UIImageView+WebCache.h"

#define iphone4 (CGSizeEqualToSize(CGSizeMake(320, 480), [UIScreen mainScreen].bounds.size))
#define iphone5 (CGSizeEqualToSize(CGSizeMake(320, 568), [UIScreen mainScreen].bounds.size))
#define iphone6 (CGSizeEqualToSize(CGSizeMake(375, 667), [UIScreen mainScreen].bounds.size))
#define iphone6plus (CGSizeEqualToSize(CGSizeMake(414, 736), [UIScreen mainScreen].bounds.size))
//默認最大輸入字數為  kMaxTextCount  300
#define kMaxTextCount 300
#define HeightVC [UIScreen mainScreen].bounds.size.height//獲取設備高度
#define WidthVC [UIScreen mainScreen].bounds.size.width//獲取設備寬度

@interface EvaluateViewController ()<UIScrollViewDelegate,UITextViewDelegate>
{
    float _TimeNUMX;
    float _TimeNUMY;
    int _FontSIZE;
    float allViewHeight;
    //備注文本View高度
    float noteTextHeight;
}

/**
 *  主視圖-
 */
@property (nonatomic, strong) UIScrollView *mianScrollView;
@property (nonatomic, strong) BRPlaceholderTextView *noteTextView;
//背景
@property (nonatomic, strong) UIView *noteTextBackgroudView;
//文字個數提示label
@property (nonatomic, strong) UILabel *textNumberLabel;
//圖片
@property (nonatomic,strong) UIImageView *photoImageView;
//文字介紹
@property (nonatomic,copy) NSString *typeStr;
@property (nonatomic,copy) NSString *upPeople;
@property (nonatomic,copy) NSString *address;
@property (nonatomic,strong) UIView * lineVCThree;
@property (nonatomic,strong) UIButton * sureBtn;
@property (nonatomic,strong) NSMutableDictionary * upDic;
@property (nonatomic,strong) NSMutableArray * photoArr;
@property (nonatomic,copy)   NSString * photoStr;
@property (nonatomic,copy)   NSString * star_level;
@property (nonatomic,copy)   NSString * modelUrl;

@end

@implementation EvaluateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.navigationItem.title = @"評價";

    self.modelUrl = @"圖片地址";
    self.typeStr = @"類型";
    self.upPeople = @"上傳者";
    self.address = @"地  址 : %@";

    //收起鍵盤
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];

    self.star_level = @"1";

    //監聽鍵盤出現和消失
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    _TimeNUMX = [self BackTimeNUMX];
    _TimeNUMY = [self BackTimeNUMY];

    [self createUI];
}

/**
 *  取消輸入
 */
- (void)viewTapped{
    [self.view endEditing:YES];
}
#pragma mark 鍵盤出現
-(void)keyboardWillShow:(NSNotification *)note
{
    self.view.frame = CGRectMake(0, 0-200*_TimeNUMY, WidthVC,HeightVC);
}
#pragma mark 鍵盤消失
-(void)keyboardWillHide:(NSNotification *)note
{
    self.view.frame = CGRectMake(0, 0, WidthVC, HeightVC);
}

- (void)createUI{
    _mianScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WidthVC, HeightVC)];
    _mianScrollView.contentSize =CGSizeMake(WidthVC, HeightVC);
    _mianScrollView.bounces =YES;
    _mianScrollView.showsVerticalScrollIndicator = false;
    _mianScrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:_mianScrollView];
    [_mianScrollView setDelegate:self];
    self.showInView = _mianScrollView;

    /** 初始化collectionView */
    [self initPickerView];

    [self initViews];
}

/**
 *  初始化視圖
 */
- (void)initViews{
    _noteTextBackgroudView = [[UIView alloc]init];
    _noteTextBackgroudView.backgroundColor = [UIColor whiteColor];

    ///照片
    self.photoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20*_TimeNUMX, 20*_TimeNUMY, 80*_TimeNUMX, 90*_TimeNUMY)];
    [self.photoImageView sd_setImageWithURL:[NSURL URLWithString:self.modelUrl] placeholderImage:[UIImage imageNamed:@"plus"]];
    UIButton * clickImageBtn = [[UIButton alloc] initWithFrame:CGRectMake(20*_TimeNUMX, 20*_TimeNUMY, 80*_TimeNUMX, 90*_TimeNUMY)];
    [clickImageBtn addTarget:self action:@selector(ClickImage:) forControlEvents:UIControlEventTouchUpInside];
    clickImageBtn.backgroundColor = [UIColor clearColor];

    ///詳情
    NSArray * infoArr = @[self.typeStr,self.upPeople];
    for (int i = 0; i<infoArr.count; i++) {
        UILabel * infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(120*_TimeNUMX, 20*_TimeNUMY+30*_TimeNUMY*i, WidthVC-120*_TimeNUMX, 30*_TimeNUMY)];
        infoLabel.text = infoArr[i];
        infoLabel.font = [UIFont systemFontOfSize:14.0+_FontSIZE];
        [_noteTextBackgroudView addSubview:infoLabel];
    }
    UILabel * info3Label = [[UILabel alloc] initWithFrame:CGRectMake(120*_TimeNUMX, 80*_TimeNUMY, WidthVC-120*_TimeNUMX, 40*_TimeNUMY)];
    info3Label.numberOfLines = 0;
    info3Label.text = self.address;
    info3Label.font = [UIFont systemFontOfSize:14.0+_FontSIZE];
    [_noteTextBackgroudView addSubview:info3Label];

    UIView * lineVCOne = [[UIView alloc] initWithFrame:CGRectMake(0, 130*_TimeNUMY, WidthVC, 10*_TimeNUMY)];
    lineVCOne.backgroundColor = [UIColor groupTableViewBackgroundColor];

    UILabel * evaluateLabel = [[UILabel alloc] initWithFrame:CGRectMake(20*_TimeNUMX, lineVCOne.frame.origin.y+lineVCOne.frame.size.height+10*_TimeNUMY, 50*_TimeNUMX, 30*_TimeNUMY)];
    evaluateLabel.text = @"總體";
    evaluateLabel.font = [UIFont systemFontOfSize:14.0+_FontSIZE];

    UIView * rView = [[UIView alloc]initWithFrame:CGRectMake(80*_TimeNUMX, lineVCOne.frame.origin.y+lineVCOne.frame.size.height+5*_TimeNUMY, 150*_TimeNUMX, 40*_TimeNUMY)];
    //    rView.ratingType = INTEGER_TYPE;//整顆星
    //    rView.delegate = self;

    UIView * lineVCTwo = [[UIView alloc] initWithFrame:CGRectMake(0, evaluateLabel.frame.origin.y+evaluateLabel.frame.size.height+10*_TimeNUMY, WidthVC, 10*_TimeNUMY)];
    lineVCTwo.backgroundColor = [UIColor groupTableViewBackgroundColor];

    //文本輸入框
    _noteTextView = [[BRPlaceholderTextView alloc]init];
    _noteTextView.keyboardType = UIKeyboardTypeDefault;
    //文字樣式
    [_noteTextView setFont:[UIFont fontWithName:@"Heiti SC" size:15.5]];
    _noteTextView.maxTextLength = kMaxTextCount;
    [_noteTextView setTextColor:[UIColor blackColor]];
    _noteTextView.delegate = self;
    _noteTextView.font = [UIFont boldSystemFontOfSize:15.5];
    _noteTextView.placeholder= @"    來分享您...";
    self.noteTextView.returnKeyType = UIReturnKeyDone;
    [self.noteTextView setPlaceholderColor:[UIColor lightGrayColor]];
    [self.noteTextView setPlaceholderOpacity:1];
    _noteTextView.textContainerInset = UIEdgeInsetsMake(5, 15, 5, 15);

    _textNumberLabel = [[UILabel alloc]init];
    _textNumberLabel.textAlignment = NSTextAlignmentRight;
    _textNumberLabel.font = [UIFont boldSystemFontOfSize:12];
    _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    _textNumberLabel.backgroundColor = [UIColor whiteColor];
    _textNumberLabel.text = [NSString stringWithFormat:@"0/%d    ",kMaxTextCount];

    self.lineVCThree = [[UIView alloc] init];
    self.lineVCThree.backgroundColor = [UIColor groupTableViewBackgroundColor];

    //確定按鈕
    self.sureBtn = [[UIButton alloc] init];
    self.sureBtn.backgroundColor = [UIColor orangeColor];
    [self.sureBtn setTitle:@"確定" forState:UIControlStateNormal];
    self.sureBtn.titleLabel.font = [UIFont systemFontOfSize:17.0+_FontSIZE];
    [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sureBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = 5.0;
    [self.sureBtn addTarget:self action:@selector(ClickSureBtn:) forControlEvents:UIControlEventTouchUpInside];

    [_mianScrollView addSubview:_noteTextBackgroudView];
    [_mianScrollView addSubview:_noteTextView];
    [_mianScrollView addSubview:_textNumberLabel];
    [_mianScrollView addSubview:self.lineVCThree];
    [_mianScrollView addSubview:self.sureBtn];

    [_noteTextBackgroudView addSubview:self.photoImageView];
    [_noteTextBackgroudView addSubview:clickImageBtn];
    [_noteTextBackgroudView addSubview:lineVCOne];
    [_noteTextBackgroudView addSubview:evaluateLabel];
    [_noteTextBackgroudView addSubview:rView];
    [_noteTextBackgroudView addSubview:lineVCTwo];

    [self updateViewsFrame];

}

/**
 *  界面布局 frame
 */
- (void)updateViewsFrame{

    if (!allViewHeight) {
        allViewHeight = 0;
    }
    if (!noteTextHeight) {
        noteTextHeight = 150*_TimeNUMY;
    }

    _noteTextBackgroudView.frame = CGRectMake(0, 0, WidthVC, 200*_TimeNUMY);

    //文本編輯框
    _noteTextView.frame = CGRectMake(0, _noteTextBackgroudView.frame.origin.y+_noteTextBackgroudView.frame.size.height+10*_TimeNUMY, WidthVC, noteTextHeight);

    //文字個數提示Label
    _textNumberLabel.frame = CGRectMake(0, _noteTextView.frame.origin.y + _noteTextView.frame.size.height-15*_TimeNUMY      , WidthVC-10*_TimeNUMX, 15*_TimeNUMY);

    self.lineVCThree.frame = CGRectMake(0*_TimeNUMX,_noteTextView.frame.origin.y+_noteTextView.frame.size.height, WidthVC, 10*_TimeNUMY);

    //photoPicker
    [self updatePickerViewFrameY:self.lineVCThree.frame.origin.y + self.lineVCThree.frame.size.height];

    self.sureBtn.frame = CGRectMake(20*_TimeNUMX, [self getPickerViewFrame].origin.y+[self getPickerViewFrame].size.height+30*_TimeNUMY, WidthVC-40*_TimeNUMX, 40*_TimeNUMY);

    allViewHeight = self.sureBtn.frame.origin.y+self.sureBtn.frame.size.height+10*_TimeNUMY;

    _mianScrollView.contentSize = self.mianScrollView.contentSize = CGSizeMake(0,allViewHeight);
}
/**
 *  恢復原始界面布局
 */
-(void)resumeOriginalFrame{
    _noteTextBackgroudView.frame = CGRectMake(0, 0, WidthVC, 200*_TimeNUMY);
    //文本編輯框
    _noteTextView.frame = CGRectMake(0, 40*_TimeNUMY, WidthVC, noteTextHeight);

    //文字個數提示Label
    _textNumberLabel.frame = CGRectMake(0, _noteTextView.frame.origin.y + _noteTextView.frame.size.height-15*_TimeNUMY      , WidthVC-10*_TimeNUMX, 15*_TimeNUMY);
}

- (void)pickerViewFrameChanged{
    [self updateViewsFrame];
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //當前輸入字數
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/%d    ",(unsigned long)_noteTextView.text.length,kMaxTextCount];
    if (_noteTextView.text.length > kMaxTextCount) {
        _textNumberLabel.textColor = [UIColor redColor];
    }else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    [self textChanged];
    return YES;
}

//文本框每次輸入文字都會調用  -> 更改文字個數提示框
- (void)textViewDidChangeSelection:(UITextView *)textView{
    //
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/%d    ",(unsigned long)_noteTextView.text.length,kMaxTextCount];
    if (_noteTextView.text.length > kMaxTextCount) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    [self textChanged];
}

/**
 *  文本高度自適應
 */
-(void)textChanged{

    CGRect orgRect = self.noteTextView.frame;//獲取原始UITextView的frame

    //獲取尺寸
    CGSize size = [self.noteTextView sizeThatFits:CGSizeMake(self.noteTextView.frame.size.width, MAXFLOAT)];

    orgRect.size.height=size.height+10;//獲取自適應文本內容高度


    //如果文本框沒字了恢復初始尺寸
    if (orgRect.size.height > 100) {
        noteTextHeight = orgRect.size.height;
    }else{
        noteTextHeight = 100;
    }

    [self updateViewsFrame];
}

#pragma mark - UIScrollViewDelegate
//用戶向上偏移到頂端取消輸入,增強用戶體驗
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0) {
        [self.view endEditing:YES];
    }
}

#pragma mark 點擊出大圖方法
- (void)ClickImage:(UIButton *)sender{

}

#pragma mark 確定評價的方法
- (void)ClickSureBtn:(UIButton *)sender{
    if (self.noteTextView.text.length == 0 || self.noteTextView.text.length < 10) {
        NSLog(@"您的評價描述字數不夠哦!");

        return;
    }
    if (self.noteTextView.text.length > kMaxTextCount) {
        NSLog(@"您的評價描述字數太多了哦!");
        return;
    }

    self.photoArr = [[NSMutableArray alloc] initWithArray:[self getBigImageArray]];

    if (self.photoArr.count >9){
        NSLog(@"最多上傳9張照片!");

    }else if (self.photoArr.count == 0){
        NSLog(@"請上傳照片!");

    }else{
        /** 上傳的接口方法 */
    }
}

#pragma mark 返回不同型號的機器的倍數值
- (float)BackTimeNUMX {
    float numX = 0.0;
    if (iphone4) {
        numX = 320 / 375.0;
        return numX;
    }
    if (iphone5) {
        numX = 320 / 375.0;
        return numX;
    }
    if (iphone6) {
        return 1.0;
    }
    if (iphone6plus) {
        numX = 414 / 375.0;
        return numX;
    }
    return numX;
}
- (float)BackTimeNUMY {
    float numY = 0.0;
    if (iphone4) {
        numY = 480 / 667.0;
        _FontSIZE = -2;
        return numY;
    }
    if (iphone5) {
        numY = 568 / 667.0;
        _FontSIZE = -2;
        return numY;
    }
    if (iphone6) {
        _FontSIZE = 0;
        return 1.0;
    }
    if (iphone6plus) {
        numY = 736 / 667.0;
        _FontSIZE = 2;
        return numY;
    }
    return numY;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#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

最后的demo頁面樣式是這樣的

Untitled.gif

 

來自:http://www.jianshu.com/p/cc710d0e6553

 

 本文由用戶 HarveyDMIJ 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!