I understand that the title is a bit confusing so I'll try my best to explain it well. I have a UIView that has a fixed width of 100, and a variable height that starts at 0. What I want to be able to do is drag my finger from the base of the UIView, towards the top of the screen, and the UIView changes its height/extends to the position of my finger. If that's still to complicated just imagine it as a strip of paper being pulled out from under something.
If you can help, that would be really great. I don't think it should be too hard, but I'm only a beginner and I can understand if I haven't explained it well!
This should be straight-forward with a UIPanGestureRecognizer and a little math. To change the view to the correct frame (I'm using the name _viewToChange, so replace that with your view later), simply add:
UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(pan:)];
pan.maximumNumberOfTouches = pan.minimumNumberOfTouches = 1;
[self addGestureRecognizer:pan];
to your init method for the super view, and define the method:
- (void)pan:(UIPanGestureRecognizer *)aPan; {
CGPoint currentPoint = [aPan locationInView:self];
[UIView animateWithDuration:0.01f
animations:^{
CGRect oldFrame = _viewToChange.frame;
_viewToChange.frame = CGRectMake(oldFrame.origin.x, currentPoint.y, oldFrame.size.width, ([UIScreen mainScreen].bounds.size.height - currentPoint.y));
}];
}
This should animate the view up as the users finger moves. Hope that Helps!
Swift version using UIPanGestureRecognizer
Using PanGesture added to UIView from Storyboard and delegate set to self.
UIView is attached to bottom of the screen.
class ViewController: UIViewController {
var translation: CGPoint!
var startPosition: CGPoint! //Start position for the gesture transition
var originalHeight: CGFloat = 0 // Initial Height for the UIView
var difference: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
originalHeight = dragView.frame.height
}
#IBOutlet weak var dragView: UIView! // UIView with UIPanGestureRecognizer
#IBOutlet var gestureRecognizer: UIPanGestureRecognizer!
#IBAction func viewDidDragged(_ sender: UIPanGestureRecognizer) {
if sender.state == .began {
startPosition = gestureRecognizer.location(in: dragView) // the postion at which PanGestue Started
}
if sender.state == .began || sender.state == .changed {
translation = sender.translation(in: self.view)
sender.setTranslation(CGPoint(x: 0.0, y: 0.0), in: self.view)
let endPosition = sender.location(in: dragView) // the posiion at which PanGesture Ended
difference = endPosition.y - startPosition.y
var newFrame = dragView.frame
newFrame.origin.x = dragView.frame.origin.x
newFrame.origin.y = dragView.frame.origin.y + difference //Gesture Moving Upward will produce a negative value for difference
newFrame.size.width = dragView.frame.size.width
newFrame.size.height = dragView.frame.size.height - difference //Gesture Moving Upward will produce a negative value for difference
dragView.frame = newFrame
}
if sender.state == .ended || sender.state == .cancelled {
//Do Something
}
}
}
This is my swift solution in doing it using autolayout and a height constraint on the view you want to resize, while setting a top and bottom limit based on the safe areas
private var startPosition: CGPoint!
private var originalHeight: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(viewDidDrag(_:)))
resizableView.addGestureRecognizer(panGesture)
}
#objc private func viewDidDrag(_ sender: UIPanGestureRecognizer) {
if sender.state == .began {
startPosition = sender.location(in: self.view)
originalHeight = detailsContainerViewHeight.constant
}
if sender.state == .changed {
let endPosition = sender.location(in: self.view)
let difference = endPosition.y - startPosition.y
var newHeight = originalHeight - difference
if view.bounds.height - newHeight < topSafeArea + backButtonSafeArea {
newHeight = view.bounds.height - topSafeArea - backButtonSafeArea
} else if newHeight < routeDetailsHeaderView.bounds.height + bottomSafeArea {
newHeight = routeDetailsHeaderView.bounds.height
}
resizableView.constant = newHeight
}
if sender.state == .ended || sender.state == .cancelled {
//Do Something if interested when dragging ended.
}
}
Related
I am trying to move the bottom view up/ down using a pan gesture. It worked but has an issue of flickering and therefore it's not a smooth transition.
Here is the code
#IBOutlet weak var bottomViewHeight: NSLayoutConstraint!
#IBOutlet weak var bottomView: UIView!
var maxHeight: CGFloat = 297
var minHeight: CGFloat = 128
let panGest = PanVerticalScrolling(target: self, action: #selector(panAction(sender:)))
bottomView.addGestureRecognizer(panGest)
#objc func panAction(sender: UIPanGestureRecognizer) {
if sender.state == .changed {
let endPosition = sender.location(in: self.bottomView)
let differenceHeight = maxHeight - endPosition.y
if differenceHeight < maxHeight && differenceHeight > minHeight {
bottomViewHeight.constant = differenceHeight
self.bottomView.layoutIfNeeded()
}
}
}
Here is the gesture class
class PanVerticalScrolling : UIPanGestureRecognizer {
override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if state == .began {
let vel = velocity(in: self.view)
if abs(vel.x) > abs(vel.y) {
state = .cancelled
}
}
}
}
And here in the image, you can check the actual issue
The problem is that you are repeatedly getting the touch position in the bottom view ... and then changing bottom view size.
Since the touch Y is relative to the height of the view, it's bouncing around.
Try this...
Add a class property:
var initialY: CGFloat = -1.0
and change your panAction() to this:
#objc func panAction(sender: UIPanGestureRecognizer) {
if sender.state == .changed {
if initialY == -1.0 {
initialY = sender.location(in: self.view).y
}
let endPositionY = sender.location(in: self.view).y - initialY
let differenceHeight = maxHeight - endPositionY
if differenceHeight < maxHeight && differenceHeight > minHeight {
bottomViewHeight.constant = differenceHeight
self.bottomView.layoutIfNeeded()
}
}
}
You'll need to reset initialY to -1 each time you "end" the drag / resize process.
Edit
A better way - maintains current state:
// these will be used inside panAction()
var initialY: CGFloat = -1.0
var initialHeight: CGFloat = -1.0
#objc func panAction(sender: UIPanGestureRecognizer) {
if sender.state == .changed {
let endPositionY = sender.location(in: self.view).y - initialY
let differenceHeight = self.initialHeight - endPositionY
if differenceHeight < maxHeight && differenceHeight > minHeight {
bottomViewHeight.constant = differenceHeight
}
}
if sender.state == .began {
// reset position and height tracking properties
self.initialY = sender.location(in: self.view).y
self.initialHeight = bottomViewHeight.constant
}
}
I thought it was a basic feature of UISplitViewController to allow resizing master/detail views by dragging the divider line. After reading the documentation, I found that it isn't possible on iOS apps. However, I did find apps on iOS that have SplitView's with draggable divider for resizing the master/detail view.
Has anyone done it? If yes, could you please help me with some pointers. Thanks in advance.
I am not sure if this answers your query but a small code using adding just a simple UISwipeGestureRecognizer to your MasterViewController's view.
If you are iOS 8.0 or later, you can use minimumPrimaryColumnWidth and maximumPrimaryColumnWidth , alongwith preferredPrimaryColumnWidthFraction.
I have added left and right Swipe gesture recognizer to the View of MasterViewController.
#IBAction func swipeGesture(_ sender: UISwipeGestureRecognizer) {
if sender.direction == .left {
UIView.animate(withDuration: 0.4) {
self.splitViewController?.minimumPrimaryColumnWidth = 200.0
self.splitViewController?.preferredPrimaryColumnWidthFraction = 0.0
self.splitViewController?.maximumPrimaryColumnWidth = 320.0
}
} else if sender.direction == .right {
UIView.animate(withDuration: 0.4) {
self.splitViewController?.minimumPrimaryColumnWidth = 200.0
self.splitViewController?.preferredPrimaryColumnWidthFraction = 1.0
self.splitViewController?.maximumPrimaryColumnWidth = 320.0
}
}
}
You can also try with pan Gesture too, as listed below to get fine control of the touch movements.
let maximumPossibleWidth:CGFloat = 320.0
var beganPoint:CGFloat = 320.0
#IBAction func panGesture(_ sender: UIPanGestureRecognizer){
if sender.state == .began {
//Began
beganPoint = sender.location(in: sender.view).x
return
}
if sender.state == .changed {
let currentPoint = sender.location(in: sender.view).x
let fraction = currentPoint / maximumPossibleWidth
if beganPoint > currentPoint {
//left
self.splitViewController?.minimumPrimaryColumnWidth = 100.0
self.splitViewController?.preferredPrimaryColumnWidthFraction = fraction
self.splitViewController?.maximumPrimaryColumnWidth = 320.0
}else {
//right
self.splitViewController?.minimumPrimaryColumnWidth = 100.0
self.splitViewController?.preferredPrimaryColumnWidthFraction = fraction
self.splitViewController?.maximumPrimaryColumnWidth = 320.0
}
}
}
I want to drag and zoom UIImageView inside UIView not in UIViewController (self.view) using swift 3.0.
Here I have declare mainView and imageView,
var lastScale: CGFloat = 0.0
#IBOutlet var mainView: UIView!
#IBOutlet var imageView: UIImageView!
I have set Pan and Pinch Gesture for zoom and drag imageview inside mainView
let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(ViewController.handlePinchGesture(_:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(pinchGestureRecognizer)
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePanGesture(recognizer:)))
imageView.addGestureRecognizer(panGestureRecognizer)
Function for pan and pinch gesture
func handlePinchGesture(_ gestureRecognizer: UIPinchGestureRecognizer) {
if gestureRecognizer.state == .began {
lastScale = gestureRecognizer.scale
}
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
let currentScale: CGFloat = (gestureRecognizer.view!.layer.value(forKeyPath: "transform.scale")! as! CGFloat)
// Constants to adjust the max/min values of zoom
//let kMaxScale: CGFloat = 2.0
let kMinScale: CGFloat = 1.0
var newScale: CGFloat = 1 - (lastScale - gestureRecognizer.scale)
//newScale = min(newScale, kMaxScale / currentScale)
newScale = max(newScale, kMinScale / currentScale)
let transform = gestureRecognizer.view?.transform.scaledBy(x: newScale, y: newScale)
gestureRecognizer.view?.transform = transform!
lastScale = gestureRecognizer.scale
}
}
func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: mainView)
var recognizerFrame = recognizer.view?.frame
recognizerFrame?.origin.x += translation.x
recognizerFrame?.origin.y += translation.y
// Check if UIImageView is completely inside its superView
if mainView.bounds.contains(recognizerFrame!) {
recognizer.view?.frame = recognizerFrame!
}
else {
// Check vertically
if (recognizerFrame?.origin.y)! < mainView.bounds.origin.y {
recognizerFrame?.origin.y = 0
}
else if (recognizerFrame?.origin.y)! + (recognizerFrame?.size.height)! > mainView.bounds.size.height {
recognizerFrame?.origin.y = mainView.bounds.size.height - (recognizerFrame?.size.height)!
}
// Check horizantally
if (recognizerFrame?.origin.x)! < mainView.bounds.origin.x {
recognizerFrame?.origin.x = 0
}
else if (recognizerFrame?.origin.x)! + (recognizerFrame?.size.width)! > mainView.bounds.size.width {
recognizerFrame?.origin.x = mainView.bounds.size.width - (recognizerFrame?.size.width)!
}
}
// Reset translation so that on next pan recognition
// we get correct translation value
recognizer.setTranslation(CGPoint(x: CGFloat(0), y: CGFloat(0)), in: mainView)
}
When I run this code, And I'm zoom imageView it's go outside of mainView.
So, How can I fixed?
Whenever you scale your subview or move your subview, the frame value of subview needs to be changed. Because frame is a property of UIView, you can use KVO to observe it and set some rules for its changes like your way done for pan etc.
For KVO of frame, you can find better explanation from here
I've published iOS app in swift whose main functions are:
1) add a photo / take a photo
2) add emoji on the photo
3) zoom, rotate, drag emoji to decorate photo
4) share it on instagram.
Emojis can be rotated, zoomed, and dragged. I've implemented these functions using UIGestureRecognizers such as UIRoationGestrueRecognizer, UIPinchGestureRecognizer, and UIPanGesstureRecognizer.
Now I am trying to update app with snapchat-like pinch zoom feature where users can zoom in / out emojis between two fingers to the extreme. Current pinch gesture works only when users' fingers are on the imageView (emoji).
Any idea / example code how to do snapchat-like pinch zoom? Below codes are how I handled rotation, pinch, and drag. Thanks in advance.
// UI Gesture Recognizers
#IBAction func handlePinch(recognizer : UIPinchGestureRecognizer) {
if(deleteMode) {
return
}
if let view = recognizer.view {
view.transform = CGAffineTransformScale(view.transform,
recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}
#IBAction func handleRotate(recognizer : UIRotationGestureRecognizer) {
if(deleteMode) {
return
}
if let view = recognizer.view {
view.transform = CGAffineTransformRotate(view.transform, recognizer.rotation)
recognizer.rotation = 0
}
}
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
if(deleteMode) {
return
}
let translation = recognizer.translationInView(self.view)
var centerX: CGFloat!
var centerY: CGFloat!
if let view = recognizer.view {
// limit the boundary - using backgroundPanel.frame.width, height, origin.x, origin.y
if(view.center.x + translation.x < panelBackground.frame.origin.x) {
centerX = view.center.x + translation.x + 10
} else if(view.center.x > panelBackground.frame.size.width){
centerX = view.center.x + translation.x - 10
} else {
centerX = view.center.x + translation.x
}
if(view.center.y < panelBackground.frame.origin.y - 60){
// set y that I can use below
centerY = view.center.y + translation.y + 10
} else if(view.center.y > panelBackground.frame.size.height){
centerY = view.center.y + translation.y - 10
} else {
centerY = view.center.y + translation.y
}
// set final position
view.center = CGPoint(x:centerX,
y:centerY)
recognizer.setTranslation(CGPointZero, inView: self.view)
}
}
#IBAction func handleLongPress(recognizer: UILongPressGestureRecognizer) {
if(recognizer.state == UIGestureRecognizerState.Began) {
if(!deleteMode) {
print("LongPress - Delete Shows")
for (_, stickers) in self.backgroundImage.subviews.enumerate() {
for (_, deleteButtons) in stickers.subviews.enumerate() {
if let delete:UIImageView = deleteButtons as? UIImageView{
if(delete.accessibilityIdentifier == "delete") {
delete.alpha = 0.5
}
}
}
}
deleteMode = true
} else {
deleteButtonHides()
}
}
}
I'm also looking drag, pan and zoom at the same time like snapchat but if you are just looking for zoom. I'm using below function for a label to zoom via pinch. It is not smooth but do the zooming job.
func handlePinch(recognizer: UIPinchGestureRecognizer) {
if let view = recognizer.view as? UILabel {
let pinchScale: CGFloat = recognizer.scale
view.transform = view.transform.scaledBy(x: pinchScale, y: pinchScale)
recognizer.scale = 1.0
}
}
For drag,pan and zoom at the same time, checkout my below post:
Pinch, drag and pan at the same time
To achieve this snapchat like pinch zooming, add pinch gesture on Parent view also and instead of recognizer transform the selected sticker as written below:
#objc func mainImgPinchGesture(_ recognizer: UIPinchGestureRecognizer) {
print("----pinchGestureAction")
if let view = recognizer.view {
if selectedSubView != nil{
self.selectedSubView.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
self.selectedSubView.contentScaleFactor = 1
}
}
}
Im trying to set up a UIPanGestureRecognizer to a specific UIView
self.halfViewBlue.frame = CGRectMake(0, 0, self.bounds.width / 2, self.bounds.height)
self.halfViewBlue.backgroundColor = UIColor.blueColor()
halfViewBlue.alpha = 1.0
self.addSubview(self.halfViewBlue)
self.halfViewRed.frame = CGRectMake(self.frame.midX, 0, self.bounds.width / 2, self.bounds.height)
self.halfViewRed.backgroundColor = UIColor.redColor()
halfViewRed.alpha = 1.0
self.addSubview(self.halfViewRed)
//Pan Gesture for Red
let panGestureRed = UIPanGestureRecognizer()
panGestureRed.addTarget(self, action: "handlePanRed:")
self.addGestureRecognizer(panGestureRed)
self.userInteractionEnabled = true
//Pan Gesture for Blue
let panGestureBlue = UIPanGestureRecognizer()
panGestureBlue.addTarget(self, action: "handlePanBlue:")
self.addGestureRecognizer(panGestureBlue)
self.userInteractionEnabled = true
}
func handlePanRed(gesture : UIPanGestureRecognizer){
if (gesture.state == UIGestureRecognizerState.Changed || gesture.state == UIGestureRecognizerState.Ended){
let velocity : CGPoint = gesture.velocityInView(halfViewRed)
//Pan Down
if(velocity.y > 0){
print("Panning down")
hideRedBar()
produceBlueBar()
}
//Pan Up
if(velocity.y < 0){
print("panning up")
hideBlueBar()
produceRedBar()
}
}
}
func handlePanBlue(gesture : UIPanGestureRecognizer){
if (gesture.state == UIGestureRecognizerState.Changed || gesture.state == UIGestureRecognizerState.Ended){
let velocity : CGPoint = gesture.velocityInView(halfViewBlue)
//Pan Down
if(velocity.y > 0){
print("Panning down")
hideBlueBar()
produceRedBar()
}
if(velocity.y < 0){
print("panning up")
hideRedBar()
produceBlueBar()
}
}
}
Here I simply create two UIViews, both split vertically across the screen(equally).
I then add two panGestures and a function to follow it. My issue is that the only panGesture that gets recognized is the "panGestureBlue" and weirdly i can control it on any part of the screen, not just the half where the "halfViewBlue" is.
So I'm assuming that both panGestures are being added to self.view and not the UIView it is suppose to be put with, and the "panGestureBlue" is being read in because it is added after "panGestureRed". Instead of "self" in the "panGestureBlue.addTarget" i tried putting "halfViewBlue", but it crashed.
How can i fix this issue!?
You should add the pan gesture on the subviews not the superview, like this:
self.halfViewRed.addGestureRecognizer(panGestureRed)
self.halfViewBlue.addGestureRecognizer(panGestureBlue)