UICollectionView - Horizontal AutoScroll with Timer - objective-c

I am using Horizontal Auto Scroll using timer. I want it to scroll one by one.
In my case it is scrolling continuos from left to right. and in last it also scroll white space after last cell.
#interface AccountsVC ()<UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
CGFloat width_Cell;
NSTimer *autoScrollTimer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
width_Cell = 0.0;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self configAutoscrollTimer];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[self deconfigAutoscrollTimer];
}
- (void)configAutoscrollTimer
{
autoScrollTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
}
- (void)deconfigAutoscrollTimer
{
[autoScrollTimer invalidate];
autoScrollTimer = nil;
}
- (void)onTimer
{
[self autoScrollView];
}
- (void)autoScrollView
{
CGPoint initailPoint = CGPointMake(width_Cell, 0);
if (CGPointEqualToPoint(initailPoint, self.collectionView.contentOffset))
{
if (width_Cell < self.collectionView.contentSize.width)
{
width_Cell += 0.5;
}else
{
width_Cell = -self.view.frame.size.width;
}
CGPoint offsetPoint = CGPointMake(width_Cell, 0);
self.collectionView.contentOffset = offsetPoint;
}else
{
width_Cell = self.collectionView.contentOffset.x;
}
}

In the custom class of your collectionViewCell:
self.contentView.frame = self.bounds;
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
and remove any other width calculations.

I am using like this
declare variable
var timer:Timer!
call from viewDidLoad
self.addTimer()
func addTimer() {
let timer1 = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.nextPage), userInfo: nil, repeats: true)
RunLoop.main.add(timer1, forMode: RunLoopMode.commonModes)
self.timer = timer1
}
func resetIndexPath() -> IndexPath {
let currentIndexPath = self.collectionView.indexPathsForVisibleItems.last
let currentIndexPathReset = IndexPath(item: (currentIndexPath?.item)!, section: 0)
self.collectionView.scrollToItem(at: currentIndexPathReset, at: UICollectionViewScrollPosition.left, animated: true)
return currentIndexPath!
}
func removeTimer() {
if self.timer != nil {
self.timer.invalidate()
}
self.timer = nil
}
func nextPage() {
let currentIndexPathReset:IndexPath = self.resetIndexPath()
var nextItem = currentIndexPathReset.item + 1
let nextSection = currentIndexPathReset.section
if nextItem == productImage.count{
nextItem = 0
}
var nextIndexPath = IndexPath(item: nextItem, section: nextSection)
if nextItem == 0 {
self.collectionView.scrollToItem(at: nextIndexPath, at: UICollectionViewScrollPosition.left, animated: false)
}
self.collectionView.scrollToItem(at: nextIndexPath, at: UICollectionViewScrollPosition.left, animated: true)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.addTimer()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.removeTimer()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
var visibleRect = CGRect()
visibleRect.origin = collectionView.contentOffset
visibleRect.size = collectionView.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
let visibleIndexPath: IndexPath? = collectionView.indexPathForItem(at: visiblePoint)
pageControlView.currentPage = (visibleIndexPath?.row)!
}

Related

How to return a array of names in uicollectionview cells swift 4

I am trying to insert an array of names into each of the cells as a test, but I keep getting an error when i type Example.name.text ECT. How do I return the array of names for each cell to have a name in it? Does the same work for images? My goal is to return UIImage so that each cell contains the next image in the UIImages.
class TestPage: UIViewController, UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
var collectView: UICollectionView!
var cellId = "Cell"
override func viewDidLoad() {
super.viewDidLoad()
let layout: UICollectionViewFlowLayout =
UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0,
right: 0)
layout.itemSize = CGSize(width: view.frame.width, height: 80)
collectView = UICollectionView(frame: self.view.frame,
collectionViewLayout: layout)
collectView.dataSource = self
collectView.delegate = self
collectView.register(Example.self, forCellWithReuseIdentifier:
cellId)
collectView.showsVerticalScrollIndicator = false
collectView.backgroundColor = UIColor.white
self.view.addSubview(collectView)
}
let listOfNames = ["John", "Smith", "Doe"]
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return listOfNames.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt
indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectView.dequeueReusableCell(withReuseIdentifier:
cellId, for: indexPath) as! Example
return cell
}
}
class Example: UICollectionViewCell {
let name: UILabel = {
let lb = UILabel()
lb.text = "This is a test"
lb.translatesAutoresizingMaskIntoConstraints = false
return lb
}()
// let aMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "Amajorscale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
// let bMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "bmajorscale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
//
// let cMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "c-major-scale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
//
// let dMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "d-major-scale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
//
override init(frame: CGRect) {
super.init(frame: frame)
addViews()
}
func addViews(){
addSubview(name)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat:
"H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views:
["v0" : name]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat:
"V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: [ .
"v0" : name]))
}

Remove a UIView stored in an array from superview

I know the code I need is [[Array objectAtIndex:index] removeFromSuperview]; but that doesn't work in Swift 2.
I'm trying to remove a UIView stored in an array from the superview. I know I want to remove the object at index 0. Want to remove it at the end of the for loop.
What code will work in Swift?
import UIKit
import Foundation
class PhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var tileStack = [AnyObject]()
let num = 0
//Beginning of simple image selection and display
#IBOutlet weak var displayImageView: UIImageView!
#IBOutlet weak var tiledView: UIImageView!
#IBAction func choosePicFromLibrary(sender: AnyObject) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
imagePicker.modalPresentationStyle = UIModalPresentationStyle.Popover
if (imagePicker.popoverPresentationController != nil) {
imagePicker.popoverPresentationController!.sourceView = sender as! UIButton
imagePicker.popoverPresentationController!.sourceRect = (sender as! UIButton).bounds
}
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func takePhoto(sender: AnyObject) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.delegate = self
imagePicker.modalPresentationStyle = UIModalPresentationStyle.Popover
if (imagePicker.popoverPresentationController != nil) {
imagePicker.popoverPresentationController!.sourceView = sender as! UIButton
imagePicker.popoverPresentationController!.sourceRect = (sender as! UIButton).bounds
}
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
displayImageView.image = info[UIImagePickerControllerOriginalImage] as! UIImage!
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
//Beginning of function to cut photo into 9 tiles, then display them randomly.
//cut selected image into 9 pieces and add each cropped image to tileStack array
#IBAction func randomize(sender: AnyObject) {
let selectedImageWidth = displayImageView.image!.size.width
let selectedImageHeight = displayImageView.image!.size.height
let tileSize = CGSizeMake(selectedImageWidth/3, selectedImageHeight/3)
for (var colI = 0; colI < 3; colI++)
{
for (var rowI = 0; rowI < 3; rowI += 1)
{
let tileRect = CGRectMake(CGFloat(rowI) * tileSize.width, tileSize.height * CGFloat(colI), tileSize.width, tileSize.height)
if let selectedImage = displayImageView.image
{
let tileImage = CGImageCreateWithImageInRect(selectedImage.CGImage, tileRect)
let aUItile = UIImage(CGImage: tileImage!)
tileStack.append(aUItile)
}
}
}
//display tiles in order on screen, remove 1 tile (top left, index 0), (eventually mix them up)
let frameWidth = self.view.frame.width
let frameHeight = self.view.frame.height
var xCen = (frameWidth/3)/2
var yCen = (frameHeight/3)/2
var pieceNumber = 0
for (var v = 0; v < 3; v += 1)
{
for (var h = 0; h < 3; h += 1)
{
var tiledView : UIImageView
tiledView = UIImageView(frame:CGRectMake(0, 0, frameWidth/3, (frameHeight)/3))
//tiledView.backgroundColor = UIColor.redColor()
tiledView.center = CGPointMake(xCen, yCen)
tiledView.image = tileStack[pieceNumber] as? UIImage
tiledView.userInteractionEnabled = true
self.view.addSubview(tiledView)
xCen += (frameWidth/3)
pieceNumber += 1
}
xCen = (frameWidth/3)/2
yCen += (frameHeight/3)
}
tileStack[0].removeFromSuperview()
tileStack.removeAtIndex(0)
}
In Swift 2.0, you need to call the removeFromSubview from the object that you want to remove. In your case you need the following:
dispatch_async(dispatch_get_main_queue(),
{
if self.view.subviews.count > 0
{
self.view.subviews[0].removeFromSuperview()
}
})

drag and drop uiimage into another uiimageview

I am using following code snippet to drag and drop uiimageview
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[myImageView addGestureRecognizer:panRecognizer];
-(void)move:(id)sender {
CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
firstX = [myImageView center].x;
firstY = [myImageView center].y;
}
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[myImageView setCenter:translatedPoint];
}
This code is drags the whole myImageView ,but my requirement is to just drag the uiimage and drop it into another uiimagview.myImageView should stay as it is after dragging also.just I need to drag the myImageView layer.draggable image should be transparent. Any ideas would b appreciated.
I have put little effort to achieve your output. try it
Step 1 :Define this 3 Variables in your .h file
UIImageView *ivSource1, *ivDestination2, *tempIV;
Step 2 : Initialize all the three UIImageView and add to your ViewController write it in viewDidLoad method
ivSource1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"1.jpg"]];
[ivSource1 setFrame:CGRectMake(100, 100, 100, 100)];
[ivSource1 setTag:100];
[ivSource1 setUserInteractionEnabled:YES];
[self.view addSubview:ivSource1];
ivDestination2 = [[UIImageView alloc] init];
[ivDestination2 setFrame:CGRectMake(200, 300, 100, 100)];
[ivDestination2 setTag:101];
[ivDestination2 setUserInteractionEnabled:YES];
[self.view addSubview:ivDestination2];
tempIV = [[UIImageView alloc] init];
[tempIV setFrame:CGRectMake(0, 300, 100, 100)];
[tempIV setTag:102];
[tempIV setUserInteractionEnabled:YES];
[self.view addSubview:tempIV];
Step 3 : Define following touch methods to handle movement of image for Drag & Drop
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if([[touch view] tag] == 100)
{
[tempIV setImage:ivSource1.image];
[tempIV setCenter:[touch locationInView:self.view]];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[tempIV setCenter:[touch locationInView:self.view]];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[tempIV setCenter:[touch locationInView:self.view]];
if(CGRectContainsPoint(ivDestination2.frame, [touch locationInView:self.view]))
{
[ivDestination2 setImage:tempIV.image];
}
// Remove image from dragable view
[tempIV setImage:[UIImage imageNamed:#""]];
}
With iOS 13, you can use Drag & Drop and copy/paste APIs in order to perform a drag and drop operation of a UIImage from one UIImageView to another UIImageView. According to your needs, you may choose one of the two following Swift 5.1 implementations.
#1. Using UIDragInteraction, UIDragInteractionDelegate and UIPasteConfiguration
import UIKit
class ViewController: UIViewController {
let imageView1 = UIImageView()
let imageView2 = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
imageView1.image = UIImage(named: "image")
imageView1.contentMode = .scaleAspectFit
imageView1.isUserInteractionEnabled = true
let dragInteraction = UIDragInteraction(delegate: self)
dragInteraction.isEnabled = true
imageView1.addInteraction(dragInteraction)
imageView2.contentMode = .scaleAspectFit
imageView2.isUserInteractionEnabled = true
let configuration = UIPasteConfiguration(forAccepting: UIImage.self)
imageView2.pasteConfiguration = configuration
let stackView = UIStackView(arrangedSubviews: [imageView1, imageView2])
view.addSubview(stackView)
stackView.distribution = .fillEqually
stackView.frame = view.bounds
stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
override func paste(itemProviders: [NSItemProvider]) {
_ = itemProviders.first?.loadObject(ofClass: UIImage.self, completionHandler: { (image: NSItemProviderReading?, error: Error?) in
DispatchQueue.main.async {
self.imageView2.image = image as? UIImage
}
})
}
}
extension ViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
guard let image = imageView1.image else { return [] }
let item = UIDragItem(itemProvider: NSItemProvider(object: image))
return [item]
}
}
#2. Using UIDragInteraction, UIDragInteractionDelegate, UIDropInteraction and UIDropInteractionDelegate
import UIKit
class ViewController: UIViewController {
let imageView1 = UIImageView()
let imageView2 = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
imageView1.image = UIImage(named: "image")
imageView1.contentMode = .scaleAspectFit
imageView1.isUserInteractionEnabled = true
imageView2.contentMode = .scaleAspectFit
imageView2.isUserInteractionEnabled = true
let dragInteraction = UIDragInteraction(delegate: self)
dragInteraction.isEnabled = true
imageView1.addInteraction(dragInteraction)
let dropInteraction = UIDropInteraction(delegate: self)
imageView2.addInteraction(dropInteraction)
let stackView = UIStackView(arrangedSubviews: [imageView1, imageView2])
view.addSubview(stackView)
stackView.distribution = .fillEqually
stackView.frame = view.bounds
stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
extension ViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
guard let image = imageView1.image else { return [] }
let item = UIDragItem(itemProvider: NSItemProvider(object: image))
item.localObject = image
return [item]
}
}
extension ViewController: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: UIImage.self) && session.items.count == 1
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
let dropLocation = session.location(in: view)
let operation: UIDropOperation
if imageView2.frame.contains(dropLocation) {
operation = session.localDragSession == nil ? .copy : .move
} else {
operation = .cancel
}
return UIDropProposal(operation: operation)
}
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
session.loadObjects(ofClass: UIImage.self) { imageItems in
guard let images = imageItems as? [UIImage] else { return }
self.imageView2.image = images.first
}
}
}

Recognize a path of user gesture

I'm working on an app with 9 views on screen, and I want the users to connect the views in a way they want, and record their sequence as password.
But I don't know which gesture recognizer I should use.
Should I use CMUnistrokeGestureRecognizer or combination of several swipe gesture or anything else?
Thanks.
You could use a UIPanGestureRecognizer, something like:
CGFloat const kMargin = 10;
- (void)viewDidLoad
{
[super viewDidLoad];
// create a container view that all of our subviews for which we want to detect touches are:
CGFloat containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - kMargin * 2.0;
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(kMargin, kMargin, containerWidth, containerWidth)];
container.backgroundColor = [UIColor darkGrayColor];
[self.view addSubview:container];
// now create all of the subviews, specifying a tag for each; and
CGFloat cellWidth = (containerWidth - (4.0 * kMargin)) / 3.0;
for (NSInteger column = 0; column < 3; column++)
{
for (NSInteger row = 0; row < 3; row++)
{
UIView *cell = [[UIView alloc] initWithFrame:CGRectMake(kMargin + column * (cellWidth + kMargin),
kMargin + row * (cellWidth + kMargin),
cellWidth, cellWidth)];
cell.tag = row * 3 + column;
cell.backgroundColor = [UIColor lightGrayColor];
[container addSubview:cell];
}
}
// finally, create the gesture recognizer
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:#selector(handlePan:)];
[container addGestureRecognizer:pan];
}
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
// an example of the sort of graphical flourish to give the
// some visual cue that their going over the subview in question
// was recognized
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
NSLog(#"We went over:");
for (UIView *subview in gesturedSubviews)
{
NSLog(#" %d", subview.tag);
}
// you might as well clean up your static variable when you're done
gesturedSubviews = nil;
}
}
Obviously, you would create your subviews any way you want, and keep track of them any way you want, but the idea is to have subviews with unique tag numbers, and the gesture recognizer would just see which order you go over them in a single gesture.
Even if I didn't capture precisely what you want, it at least shows you how you can use a pan gesture recognizer to track the movement of your finger from one subview to another.
Update:
If you wanted to draw a path on the screen as the user is signing in, you could create a CAShapeLayer with a UIBezierPath. I'll demonstrate that below, but as a caveat, I feel compelled to point out that this might not be a great security feature: Usually with password entry, you'll show the user enough so that they can confirm that they're doing what they want, but not enough so that someone can glance look over their shoulder and see what the whole password was. When entering a text password, usually iOS momentarily shows you the last key you hit, but quickly turns that into an asterisk so that, at no point, can you see the whole password. Hence my initial suggestion.
But if you really have your heart set on showing the user the path as they draw it, you could use something like the following. First, this requires Quartz 2D. Thus add the QuartzCore.framework to your project (see Linking to a Library or Framework). Second, import the QuartCore headers:
#import <QuartzCore/QuartzCore.h>
Third, replace the pan handler with something like:
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
static UIBezierPath *path = nil;
static CAShapeLayer *shapeLayer = nil;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (!path)
{
// if the path hasn't be started, initialize it and the shape layer
path = [UIBezierPath bezierPath];
[path moveToPoint:location];
shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineWidth = 2.0;
[gesture.view.layer addSublayer:shapeLayer];
}
else
{
// otherwise add this point to the layer's path
[path addLineToPoint:location];
shapeLayer.path = path.CGPath;
}
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
// assuming the tags are numbers between 0 and 9 (inclusive), we can build the password here
NSMutableString *password = [NSMutableString string];
for (UIView *subview in gesturedSubviews)
[password appendFormat:#"%c", subview.tag + 48];
NSLog(#"Password = %#", password);
// clean up our array of gesturedSubviews
gesturedSubviews = nil;
// clean up the drawing of the path on the screen the user drew
[shapeLayer removeFromSuperlayer];
shapeLayer = nil;
path = nil;
}
}
That yields a path that the user draws as the gesture proceeds:
Rather than showing the path the user draws with each and every movement of the user's finger, maybe you just draw the lines between the center of the subviews, such as:
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
static UIBezierPath *path = nil;
static CAShapeLayer *shapeLayer = nil;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
if (!path)
{
// if the path hasn't be started, initialize it and the shape layer
path = [UIBezierPath bezierPath];
[path moveToPoint:subview.center];
shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineWidth = 2.0;
[gesture.view.layer addSublayer:shapeLayer];
}
else
{
// otherwise add this point to the layer's path
[path addLineToPoint:subview.center];
shapeLayer.path = path.CGPath;
}
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
// assuming the tags are numbers between 0 and 9 (inclusive), we can build the password here
NSMutableString *password = [NSMutableString string];
for (UIView *subview in gesturedSubviews)
[password appendFormat:#"%c", subview.tag + 48];
NSLog(#"Password = %#", password);
// clean up our array of gesturedSubviews
gesturedSubviews = nil;
// clean up the drawing of the path on the screen the user drew
[shapeLayer removeFromSuperlayer];
shapeLayer = nil;
path = nil;
}
}
That yields something like:
You have all sorts of options, but hopefully you now have the building blocks so you can design your own solution.
Forgive me Rob, pure Plagiarism here :) Needed the same code in swift 3.0 :) so I translated this great little example you wrote into swift 3.0.
ViewController.swift
import UIKit
class ViewController: UIViewController {
static let kMargin:CGFloat = 10.0;
override func viewDidLoad()
{
super.viewDidLoad()
// create a container view that all of our subviews for which we want to detect touches are:
let containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - ViewController.kMargin * 2.0
let container = UIView(frame: CGRect(x: ViewController.kMargin, y: ViewController.kMargin, width: containerWidth, height: containerWidth))
container.backgroundColor = UIColor.darkGray
view.addSubview(container)
// now create all of the subviews, specifying a tag for each; and
let cellWidth = (containerWidth - (4.0 * ViewController.kMargin)) / 3.0
for column in 0 ..< 3 {
for row in 0 ..< 3 {
let cell = UIView(frame: CGRect(x: ViewController.kMargin + CGFloat(column) * (cellWidth + ViewController.kMargin), y: ViewController.kMargin + CGFloat(row) * (cellWidth + ViewController.kMargin), width: cellWidth, height: cellWidth))
cell.tag = row * 3 + column;
container.addSubview(cell)
}
}
// finally, create the gesture recognizer
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
container.addGestureRecognizer(pan)
}
func handlePan(gesture: UIPanGestureRecognizer)
{
var gesturedSubviews : [UIView] = []
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == .began)
{
gesturedSubviews.removeAll()
}
let location = gesture.location(in: gesture.view)
for subview in (gesture.view?.subviews)! {
if (subview.frame.contains(location)) {
if (subview != gesturedSubviews.last) {
gesturedSubviews.append(subview)
subview.backgroundColor = UIColor.blue
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state != .recognized)
{
print("We went over:");
for subview in gesturedSubviews {
print(" %d", (subview as AnyObject).tag);
}
// you might as well clean up your static variable when you're done
}
}
}
}
Update: Almost that is; I tried to translate the update too, but my translation missed something and didn't work, so I searched around SO and crafted a similar if slightly different final solution.
import UIKit
import QuartzCore
class ViewController: UIViewController {
static let kMargin:CGFloat = 10.0;
override func viewDidLoad()
{
super.viewDidLoad()
// create a container view that all of our subviews for which we want to detect touches are:
let containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - ViewController.kMargin * 2.0
let container = UIView(frame: CGRect(x: ViewController.kMargin, y: ViewController.kMargin, width: containerWidth, height: containerWidth))
container.backgroundColor = UIColor.darkGray
view.addSubview(container)
// now create all of the subviews, specifying a tag for each; and
let cellWidth = (containerWidth - (4.0 * ViewController.kMargin)) / 3.0
for column in 0 ..< 3 {
for row in 0 ..< 3 {
let cell = UIView(frame: CGRect(x: ViewController.kMargin + CGFloat(column) * (cellWidth + ViewController.kMargin), y: ViewController.kMargin + CGFloat(row) * (cellWidth + ViewController.kMargin), width: cellWidth, height: cellWidth))
cell.tag = row * 3 + column;
container.addSubview(cell)
}
}
// finally, create the gesture recognizer
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
container.addGestureRecognizer(pan)
}
// Here's a Swift 3.0 version based on Rajesh Choudhary's answer:
func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.fillColor = nil
line.lineWidth = 8
line.opacity = 0.5
line.strokeColor = UIColor.red.cgColor
layer.addSublayer(line)
}
var gesturedSubviews : [UIView] = []
var startX: CGFloat!
var startY: CGFloat!
var endX: CGFloat!
var endY: CGFloat!
func handlePan(gesture: UIPanGestureRecognizer) {
if (gesture.state == .began)
{
gesturedSubviews = [];
let location = gesture.location(in: gesture.view)
print("location \(location)")
startX = location.x
startY = location.y
}
if (gesture.state == .changed) {
let location = gesture.location(in: gesture.view)
print("location \(location)")
endX = location.x
endY = location.y
drawLine(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:endX, y:endY))
startX = endX
startY = endY
}
if (gesture.state == .ended) {
let location = gesture.location(in: gesture.view)
print("location \(location)")
drawLine(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:location.x, y:location.y))
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
let location = gesture.location(in: gesture.view)
print("location \(location)")
for subview in (gesture.view?.subviews)! {
if subview.frame.contains(location) {
if (subview != gesturedSubviews.last) {
gesturedSubviews.append(subview)
subview.backgroundColor = UIColor.blue
subview.alpha = 1.0
}
}
}
}
}

How do I animate MKAnnotationView drop?

I have a custom MKAnnotationView where I set my image myself in viewForAnnotation. How do I animate it's drop like I can with MKPinAnnotationView?
My code is
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil)
{
annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
}
annotationView.image = [UIImage imageNamed:#"blah.png"];
annotationView.annotation = annotation;
return annotationView;
}
One problem with the code above by Anna Karenina is that it doesn't deal with when you add annotations below where the user is looking at the moment. Those annotations will float in mid-air before dropping because they are moved into the user's visible map rect.
Another is that it also drops the user location blue dot. With this code below, you handle both user location and large amounts of map annotations off-screen. I've also added a nice bounce ;)
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
MKAnnotationView *aV;
for (aV in views) {
// Don't pin drop if annotation is user location
if ([aV.annotation isKindOfClass:[MKUserLocation class]]) {
continue;
}
// Check if current annotation is inside visible map rect, else go to next one
MKMapPoint point = MKMapPointForCoordinate(aV.annotation.coordinate);
if (!MKMapRectContainsPoint(self.mapView.visibleMapRect, point)) {
continue;
}
CGRect endFrame = aV.frame;
// Move annotation out of view
aV.frame = CGRectMake(aV.frame.origin.x, aV.frame.origin.y - self.view.frame.size.height, aV.frame.size.width, aV.frame.size.height);
// Animate drop
[UIView animateWithDuration:0.5 delay:0.04*[views indexOfObject:aV] options: UIViewAnimationOptionCurveLinear animations:^{
aV.frame = endFrame;
// Animate squash
}completion:^(BOOL finished){
if (finished) {
[UIView animateWithDuration:0.05 animations:^{
aV.transform = CGAffineTransformMakeScale(1.0, 0.8);
}completion:^(BOOL finished){
if (finished) {
[UIView animateWithDuration:0.1 animations:^{
aV.transform = CGAffineTransformIdentity;
}];
}
}];
}
}];
}
}
Implement the didAddAnnotationViews delegate method and do the animation yourself:
- (void)mapView:(MKMapView *)mapView
didAddAnnotationViews:(NSArray *)annotationViews
{
for (MKAnnotationView *annView in annotationViews)
{
CGRect endFrame = annView.frame;
annView.frame = CGRectOffset(endFrame, 0, -500);
[UIView animateWithDuration:0.5
animations:^{ annView.frame = endFrame; }];
}
}
#MrAlek's Answer for swift3
optional func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
print(#function)
var i = -1;
for view in views {
i += 1;
if view.annotation is MKUserLocation {
continue;
}
// Check if current annotation is inside visible map rect, else go to next one
let point:MKMapPoint = MKMapPointForCoordinate(view.annotation!.coordinate);
if (!MKMapRectContainsPoint(self.mapView.visibleMapRect, point)) {
continue;
}
let endFrame:CGRect = view.frame;
// Move annotation out of view
view.frame = CGRect(origin: CGPoint(x: view.frame.origin.x,y :view.frame.origin.y-self.view.frame.size.height), size: CGSize(width: view.frame.size.width, height: view.frame.size.height))
// Animate drop
let delay = 0.03 * Double(i)
UIView.animate(withDuration: 0.5, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations:{() in
view.frame = endFrame
// Animate squash
}, completion:{(Bool) in
UIView.animate(withDuration: 0.05, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations:{() in
view.transform = CGAffineTransform(scaleX: 1.0, y: 0.6)
}, completion: {(Bool) in
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations:{() in
view.transform = CGAffineTransform.identity
}, completion: nil)
})
})
}
}
#mrAlek answer in Swift:
func mapView(mapView: MKMapView!, didAddAnnotationViews views: [AnyObject]!) {
println("didAddAnnotationViews()")
var i = -1;
for view in views {
i++;
let mkView = view as! MKAnnotationView
if view.annotation is MKUserLocation {
continue;
}
// Check if current annotation is inside visible map rect, else go to next one
let point:MKMapPoint = MKMapPointForCoordinate(mkView.annotation.coordinate);
if (!MKMapRectContainsPoint(self.mapView.visibleMapRect, point)) {
continue;
}
let endFrame:CGRect = mkView.frame;
// Move annotation out of view
mkView.frame = CGRectMake(mkView.frame.origin.x, mkView.frame.origin.y - self.view.frame.size.height, mkView.frame.size.width, mkView.frame.size.height);
// Animate drop
let delay = 0.03 * Double(i)
UIView.animateWithDuration(0.5, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations:{() in
mkView.frame = endFrame
// Animate squash
}, completion:{(Bool) in
UIView.animateWithDuration(0.05, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations:{() in
mkView.transform = CGAffineTransformMakeScale(1.0, 0.6)
}, completion: {(Bool) in
UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations:{() in
mkView.transform = CGAffineTransformIdentity
}, completion: nil)
})
})
}
}
#MrAlek's answer in Swift 2:
func mapView(mapView: MKMapView, didAddAnnotationViews views: [MKAnnotationView]) {
print(__FUNCTION__)
var i = -1;
for view in views {
i++;
if view.annotation is MKUserLocation {
continue;
}
// Check if current annotation is inside visible map rect, else go to next one
let point:MKMapPoint = MKMapPointForCoordinate(view.annotation!.coordinate);
if (!MKMapRectContainsPoint(self.mapView.visibleMapRect, point)) {
continue;
}
let endFrame:CGRect = view.frame;
// Move annotation out of view
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y - self.view.frame.size.height, view.frame.size.width, view.frame.size.height);
// Animate drop
let delay = 0.03 * Double(i)
UIView.animateWithDuration(0.5, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations:{() in
view.frame = endFrame
// Animate squash
}, completion:{(Bool) in
UIView.animateWithDuration(0.05, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations:{() in
view.transform = CGAffineTransformMakeScale(1.0, 0.6)
}, completion: {(Bool) in
UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations:{() in
view.transform = CGAffineTransformIdentity
}, completion: nil)
})
})
}
}
Updated for Swift 4.2
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
var i = -1;
for view in views {
i += 1;
if view.annotation is MKUserLocation {
continue;
}
let point:MKMapPoint = MKMapPoint(view.annotation!.coordinate);
if (!self.mapView.visibleMapRect.contains(point)) {
continue;
}
let endFrame:CGRect = view.frame;
view.frame = CGRect(origin: CGPoint(x: view.frame.origin.x,y :view.frame.origin.y-self.view.frame.size.height), size: CGSize(width: view.frame.size.width, height: view.frame.size.height))
let delay = 0.03 * Double(i)
UIView.animate(withDuration: 0.5, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations:{() in
view.frame = endFrame
}, completion:{(Bool) in
UIView.animate(withDuration: 0.05, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations:{() in
view.transform = CGAffineTransform(scaleX: 1.0, y: 0.6)
}, completion: {(Bool) in
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions.curveEaseInOut, animations:{() in
view.transform = CGAffineTransform.identity
}, completion: nil)
})
})
}
}
Rather than implementing mapView(_:didAdd:) in the MKMapViewDelegate, you can also have the annotation view do the animation itself.
class CustomAnnotationView: MKAnnotationView {
override var annotation: MKAnnotation? { didSet { update(for: annotation) } }
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
update(for: annotation)
}
override func prepareForReuse() {
super.prepareForReuse()
removeFromSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
transform = CGAffineTransform(translationX: 0, y: -100)
alpha = 0
UIViewPropertyAnimator(duration: 0.5, dampingRatio: 0.4) {
self.transform = .identity
self.alpha = 1
}.startAnimation()
}
private func update(for annotation: MKAnnotation?) {
// do whatever update to the annotation view you want, if any
}
}
This is useful for avoiding the cluttering of one’s view controller with annotation view animations. E.g. in iOS 11 and later, you might do:
mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
And then you can add an annotation to your map view, and you get this animation of the annotation view without any more code in the view controller.
This particular animation is a drop with a little bounce at the end, but obviously you can do whatever animation you want.
The above was written in Swift, but the concept is equally valid in Objective-C, too.