[Code Note] iOS-collectionView deletes a photo,

Source: Internet
Author: User

[Code Note] iOS-collectionView deletes a photo,

I ,.

2. Engineering Drawing.

3. Code.

ViewController. h

#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{    UICollectionView *_collectionView;    UIImagePickerController *_imagePicker;    NSMutableArray *photos;    NSMutableArray *dataArray;    NSInteger deleteIndex;    BOOL wobble;}@end

 

ViewController. m

// Stop deleting when you click the Add button. # Import "ViewController. h "# import" photoCollectionViewCell. h "NSInteger const Photo = 8; @ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // The layout is very interesting. When you set the cell size, the number of cells in a row is determined by the cell width. UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init]; // set the cell Size [flowLayout setItemSize: CGSizeMake (70, 70)]; // set its layout Direction [flowLayout setScrollDirection: UICollectionViewScrollDirectionVertical]; // set its border (upper, left, bottom, right) flowLayout. sectionInset = UIEdgeInsetsMake (50,320,); _ collectionView = [[UICollectionView alloc] initWithFrame: CGRectMake (10, * 2) collectionViewLayout: flowLayout]; _ collectionView. dataSource = self; _ collectionView. delegate = self; _ collection View. backgroundColor = [UIColor redColor]; [_ collectionView registerClass: [photoCollectionViewCell class] forCellWithReuseIdentifier: @ "photo"]; [self. view addSubview: _ collectionView]; photos = [[NSMutableArray alloc] init]; dataArray = [[NSMutableArray alloc] init]; [dataArray addObject: [UIImage imageNamed: @ "contract_addpic1"];} // section-(NSInteger) numberOfSectionsInCollectionView :( UICollecti OnView *) collectionView {return 1;} // number of items-(NSInteger) collectionView :( UICollectionView *) collectionView numberOfItemsInSection :( NSInteger) section {return dataArray. count;}-(UICollectionViewCell *) collectionView :( UICollectionView *) collectionView cellForItemAtIndexPath :( NSIndexPath *) indexPath {NSLog (@ "-- indexPath. row -- % ld ", indexPath. row); NSLog (@ "--- indexpath. section -- % ld ", indexPath. section); p HotoCollectionViewCell * cell = (photoCollectionViewCell *) [collectionView dequeueReusableCellWithReuseIdentifier: @ "photo" forIndexPath: indexPath]; cell. tag = indexPath. row; // the cell of the image. photoImage. image = dataArray [indexPath. row]; // Delete the cell. deleteBtn. tag = indexPath. row; cell. deleteBtn. hidden = YES; [cell. deleteBtn addTarget: self action: @ selector (doClickDeleteButton :) forControlEvents: UIControlEventTouch UpInside]; // Add the button if (indexPath. row = dataArray. count-1) {cell. addBtn. hidden = NO;} else {cell. addBtn. hidden = YES;} [cell. addBtn addTarget: self action: @ selector (doClickAddButton :) forControlEvents: UIControlEventTouchUpInside]; // long-pressed Delete objects * longPress = [[delealloc] initWithTarget: self action: @ selector (longPressedAction)]; [cell. contentView ad Response: longPress]; return cell;} # pragma-mark-doClickActions // delete button-(void) doClickDeleteButton :( UIButton *) btn {NSLog (@ "----- doClickDeleteButton -------"); UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "prompt" message: @ "are you sure you want to delete it? "Delegate: self cancelButtonTitle: @" cancel "otherButtonTitles: @" OK ", nil]; deleteIndex = btn. tag; [alert show]; NSLog (@ "--- delete -- dataArray --- % @", dataArray);} // Add button-(void) doClickAddButton :( UIButton *) btn {NSLog (@ "----- doClickAddButton -------"); if (wobble) {// if it is in the editing status, cancel the editing status [self cancelWobble];} else {// not in the editing status. Add the image if (dataArray. count> Photo) {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "prompt" message: @ "up to 8" delegate: self cancelButtonTitle: @ "cancel" otherButtonTitles: @ "OK", nil]; [alert show];} else {UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle: nil delegate :( id) self cancelButtonTitle: @ "cancel" destructiveButtonTitle: nil otherButtonTitles: @ "", @ "my album", nil]; actionSheet. actionSheetStyle = UIActionSheetStyleBlackOpaque; [actionSheet showInView: self. view] ;}} NSLog (@ "--- add -- dataArray --- % @", dataArray);} // long-pressed Delete-(void) longPressedAction {NSLog (@ "----- longPressedAction -------"); wobble = YES; NSArray * array = [_ collectionView subviews]; for (int I = 0; I <array. count; I ++) {if ([array [I] isKindOfClass: [photoCollectionViewCell class]) {photoCollectionViewCell * cell = array [I]; if (cell. addBtn. hidden) {cell. deleteBtn. hidden = NO;} else {cell. deleteBtn. hidden = YES; cell. photoImage. image = [UIImage imageNamed: @ "ensure"]; cell. tag = 999999;} // shake animation [self animationViewCell: cell] ;}}// cancel shaking-(void) cancelWobble {wobble = NO; NSArray * array = [_ collectionView subviews]; for (int I = 0; I <array. count; I ++) {if ([array [I] isKindOfClass: [photoCollectionViewCell class]) {photoCollectionViewCell * cell = array [I]; cell. deleteBtn. hidden = YES; if (cell. tag = 999999) {cell. photoImage. image = [UIImage imageNamed: @ "plus"] ;}// shake animation [self animationViewCell: cell] ;}}// shake animation-(void) animationViewCell :( photoCollectionViewCell *) cell {// swing if (wobble) {cell. transform = transform (-0.1); [UIView animateWithDuration: 0.08 delay: 0.0 options: UIViewAnimationOptionRepeat | updated | UIViewAnimationOptionCurveLinear animations: ^ {cell. transform = complete (0.1);} completion: nil];} else {[UIView animateWithDuration: 0.25 delay: 0.0 options: UIViewAnimationOptionAllowUserInteraction | contents | required animations: ^ {cell. transform = CGAffineTransformIdentity;} completion: nil] ;}# pragma-mark-UIActionSheetDelegate-(void) actionSheet :( UIActionSheet *) actionSheet clickedButtonAtIndex :( NSInteger) buttonIndex {if (buttonIndex = 0) {[self openCamera];} else if (buttonIndex = 1) {[self openPics];} # pragma-mark-marker-(void) alertView :( UIAlertView *) alertView clickedButtonAtIndex :( NSInteger) buttonIndex {if (buttonIndex = 1) {[dataArray removeObjectAtIndex: deleteIndex]; NSIndexPath * path = [NSIndexPath indexPathForRow: deleteIndex inSection: 0]; [_ collectionView deleteItemsAtIndexPaths: @ [path]; // if the deletion is complete, cancel if (dataArray. count = 1) {[self cancelWobble];} // If the animation is not deleted, run the shaking animation else {[self longPressedAction] ;}}. # pragma-mark-camera // open the camera-(void) openCamera {if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {if (_ imagePicker = nil) {_ imagePicker = [[UIImagePickerController alloc] init];} _ imagePicker. delegate = (id) self; _ imagePicker. sourceType = UIImagePickerControllerSourceTypeCamera; _ imagePicker. showsCameraControls = YES; _ imagePicker. allowsEditing = YES; [self. navigationController presentViewController: _ imagePicker animated: YES completion: nil] ;}// open the album-(void) openPics {if (_ imagePicker = nil) {_ imagePicker = [[UIImagePickerController alloc] init];} _ imagePicker. sourceType = UIImagePickerControllerSourceTypePhotoLibrary; _ imagePicker. allowsEditing = YES; _ imagePicker. delegate = (id) self; [self presentViewController: _ imagePicker animated: YES completion: NULL];} // select the photo-(void) imagePickerController :( UIImagePickerController *) picker syntax :( NSDictionary *) info {NSString * mediaType = [info objectForKey: Encrypted]; [_ imagePicker dismissViewControllerAnimated: YES completion: NULL]; _ imagePicker = nil; // determine the acquisition type: image if ([mediaType isw.tostring: @ "public. image "]) {UIImage * theImage = nil; // determines whether the image can be modified if ([picker allowsEditing]) {// obtain the edited image theImage = [info objectForKey: UIImagePickerControllerEditedImage];} else {// The metadata parameter theImage = [info objectForKey: UIImagePickerControllerOriginalImage];} [dataArray insertObject: theImage atIndex: 0]; NSIndexPath * path = [NSIndexPath indexPathForRow: 0 inSection: 0]; [_ collectionView insertItemsAtIndexPaths: @ [path];} -(void) Authorization :( UIImagePickerController *) picker {[picker failed: YES completion: NULL];} // determines whether the device has a camera-(BOOL) isCameraAvailable {return [UIImagePickerController isSourceTypeAvailable: album] ;}# pragma mark-album file selection related // album availability-(BOOL) isPhotoLibraryAvailable {return [UIImagePickerController isSourceTypeAvailable: available] ;}- (void) didReceiveMemoryWarning {[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated .} @ end

 

PhotoCollectionViewCell. h

#import <UIKit/UIKit.h>@interface photoCollectionViewCell : UICollectionViewCell@property (weak, nonatomic) IBOutlet UIButton *addBtn;@property (weak, nonatomic) IBOutlet UIImageView *photoImage;@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;@end

 

PhotoCollectionViewCell. m

# Import "photoCollectionViewCell. h "@ implementation photoCollectionViewCell-(id) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {// load collectionCell during initialization. xib file NSArray * arrayOfViews = [[NSBundle mainBundle] loadNibNamed: @ "photoCollectionViewCell" owner: self options: nil]; // if the path does not exist, return nil if (arrayOfViews. count <1) {return nil;} // if the view in xib does not belong to UICollectionViewCell Class, return nil if (! [[ArrayOfViews objectAtIndex: 0] isKindOfClass: [UICollectionViewCell class]) {return nil;} // load nib self = [arrayOfViews objectAtIndex: 0];} return self ;} -(void) awakeFromNib {// Initialization code} @ end

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.