UIView category that adds dragging capabilities

Related tags

UI UIView-draggable
Overview

Build Status Coverage Status CocoaPods Carthage compatible

UIView category that adds dragging capabilities.

Screenshot

UIView+draggable

Setup with CocoaPods

  • Add pod 'UIView+draggable' to your Podfile
  • Run pod install
  • Run open App.xcworkspace

Setup with Carthage

github "andreamazz/UIView-draggable"

Objective-C

Import UIView+draggable.h in your controller's header file

Swift

If you are using use_frameworks! in your Podfile, use this import:

import UIView_draggable

Usage

Call enableDragging on a UIView instance

Objective-C

// Enable dragging
[self.view enableDragging];

Swift

view.enableDragging()

Options

The movement area can be restricted to a given rect:

view.cagingArea = CGRectMake(0, 0, 200, 200)

The movement can be restricted over one coordinate:

view.shouldMoveAlongX = true
view.shouldMoveAlongY = true

The area where the dragging action starts can be configured:

view.handle = CGRectMake(0, 0, 20, 20)

Author

Andrea Mazzini. I'm available for freelance work, feel free to contact me.

Want to support the development of these free libraries? Buy me a coffee ☕️ via Paypal.

Contributors

Thanks to everyone kind enough to submit a pull request.

MIT License

The MIT License (MIT)

Copyright (c) 2017 Andrea Mazzini

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Comments
  • add (id)parameter to draggingBlocks.  UIView self can be called in draggingBlocks

    add (id)parameter to draggingBlocks. UIView self can be called in draggingBlocks

    In my situation, I need to change UIView itself in draggingBlocks. And I think add (id self) in draggingBlocks is helpful.

    I'm not sure if there is any problem with it, and these code run well in my app. If I'm wrong , please tell me. Thank you

    opened by jeffssss 8
  • using setDraggingStartedBlock setDraggingEndedBlock

    using setDraggingStartedBlock setDraggingEndedBlock

    1. I though it would be fun to alter the background color & alpha of view while they moved so I tried out these blocks but the views do not land on the X,Y coords I leave them on. They jump a little. My Code is:
        __weak typeof(timerView) weakSelf = timerView;
        [timerView setDraggingStartedBlock:^
         {
             weakSelf.backgroundColor=switchColor;
             weakSelf.alpha = 0.9f;
         }];
        [timerView setDraggingEndedBlock:^
         {
             weakSelf.backgroundColor=[UIColor whiteColor];;
             weakSelf.alpha = 1.0f;
         }];
    

    Without these blocks the views stop in the correct place. Is there something I can do to resolve this? It's the EndedBlock that's the issue. Even an empty block caused the view to just at the end.

    Not mission critical, just nice to try out the code.

    bug help wanted 
    opened by sundialsoft 5
  • How to use draggingEndedBlock to know that uiview has been ended dragging?

    How to use draggingEndedBlock to know that uiview has been ended dragging?

    @andreamazz I tried to override the variable draggingStartedBlock, draggingEndedBlock with didSet in order to know when the event is fired and call a function afterwards. However, I could not figure out how I can get the notification from draggingEndedBlock and seems it is never called when I test. and the delegate function is never called as well.

    would be much appreciated if you could provide examples on how to use these variables

    Here is my code:

     override var draggingEndedBlock: ((UIView?) -> Void)!{
            didSet{
                print("drag ended")
                delegate?.updatePosition(self.frame, messageId: (self.message?.id)!)
            }
        }
    

    Anyone could help?

    question 
    opened by ZhuQinglei 4
  • When included, this pod seems to mess with UIKit's general behaviors.

    When included, this pod seems to mess with UIKit's general behaviors.

    For example, UIImagePickerController is sometimes grayed-out or unresponsive, and UIActivityViewController, when presented, has its frame off the screen. I'll have to look for more details, but I know the issue is not present in my (older) fork: https://github.com/rsmoz/UIView-draggable

    opened by rsmoz 4
  • How to drag a button without calling button action?

    How to drag a button without calling button action?

    When i stop drag a button, the button's action will called, i tryed this: [self.roundButtonShadowView setDraggingStartedBlock:^(UIView *view) { @strongify(self) self.roundButton.userInteractionEnabled = NO; }]; [self.roundButtonShadowView setDraggingEndedBlock:^(UIView *view) { @strongify(self) self.roundButton.userInteractionEnabled = YES; }]; but now worked, the button's action is still be called... Sorry for my bad English.

    opened by zkfpk6 3
  • Resetting anchor point

    Resetting anchor point

    if (sender.state == UIGestureRecognizerStateEnded && self.draggingEndedBlock) { self.layer.anchorPoint = CGPointMake(0.5, 0.5); self.draggingEndedBlock(self); }

    Just wondering why one would need to have the drag end block implemented to have the anchor point reset.

    opened by renjithn 3
  • move outside parent

    move outside parent

    Hi, could the object move/drag outside of its parent ?

    let's say uibutton added as subview in uiscrollview and I want to make the uibutton draggable in whole self.view not only inside uiscrollview

    any hint?

    opened by mrhaxic 1
  • x,y should separate judgment

    x,y should separate judgment

        if (newXOrigin <= cagingAreaOriginX ||
            newXOrigin + CGRectGetWidth(self.frame) >= cagingAreaRightSide ) {
            newXOrigin = CGRectGetMinX(self.frame);
    
        }
        if(newYOrigin <= cagingAreaOriginY ||
           newYOrigin + CGRectGetHeight(self.frame) >= cagingAreaBottomSide)
        {
                        newYOrigin = CGRectGetMinY(self.frame);
        } 
    
    opened by azureplus 1
  • Gesture recognition fix

    Gesture recognition fix

    I was having problems with small draggable views and quick pan velocities where the gesture events would end up outside of the handle rect if the gesture was quick enough. Is there a specific reason this was being checked on all event states?

    EDIT: Also apparently some Atom generated whitespace fixes?

    opened by tommybananas 1
  • Test coverage and coveralls.io integration

    Test coverage and coveralls.io integration

    Hi @andreamazz,

    I've added tests and integrated coveralls.io for your project during the CocoaPods TestJam. Please note that you will need to enable coveralls.io for the repo using your GitHub account, I don't have admin rights to do that. Check this post if you need more info on coveralls.

    We're 100% covered :)

    opened by filwag 1
  • Add caging area

    Add caging area

    This pull request adds the functionality a caging area for the draggable view, in which the view can not be dragged out of.

    To add a caging area, set the cagingArea property on the view:

    [view enableDragging];
    CGRect cagingArea = <some CGRect>;
    view.cagingArea = theCagingArea;
    

    and to disable the caging functionality, set the cagingArea to CGRectZero:

    view.cagingArea = CGRectZero;
    

    This also adds a UISwitch to the demo project to showcase this behavior. In this demo, the caging area is the frame of the FPViewController's view.

    caging

    opened by jrmsklar 1
  • Change @import to #import

    Change @import to #import

    @import directive is causing a compiler issue "Use of '@import' when C++ modules are disabled, consider using fmodules and fcxx-modules" when included in .mm files.

    opened by hyeongminan 0
  • Swipe View Fast - Out of Bounds

    Swipe View Fast - Out of Bounds

    If cagingArea is set and you swipe the view quickly it will go out of bounds, for example I turned off allowing the view to move along the Y axis, but it does if I swipe it down or up fast enough.

    Commenting out function "adjustAnchorPointForGestureRecognizer" seems to fix my issue, but still testing...

    opened by gintechsystems 1
  • Move subviews

    Move subviews

    Hi,

    I want to move the subviews of a view. Actually if I set enableDragging in a subview it doesn't move, but if I set into the superview it moves. Is there I have to config into the superview to enable pan gesture into subviews?

    Thanks for your work!

    opened by josealonsogarcia 0
  • draggingStartedBlock didn't work when UIView dragged fast enough

    draggingStartedBlock didn't work when UIView dragged fast enough

    In Demo, FPViewController.m , I use draggingStartedBlock

    - (IBAction)actionSwitch:(UISwitch*)sender {
        [self.draggableViews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
            [obj setDraggable:sender.isOn];
            obj.draggingStartedBlock= ^(){
                NSLog(@"dragging!~!~!~!");
            };
        }];
    }
    

    when I drag UIView slowly, it works well, but when I drag UIView fast enough, draggingStartedBlock doesn't work.

    I think the problem is , when - (void)handlePan:(UIPanGestureRecognizer*)sender is called, sender.state is alreay 'UIGestureRecognizerStateChanged' . I'm not sure and I wonder whether there are some good solutions.

    THANK YOU.

    opened by jeffssss 1
Owner
Andrea Mazzini
💻 Software Engineer 🌲 Woodworker
Andrea Mazzini
A library, which adds the ability to hide navigation bar when view controller is pushed via hidesNavigationBarWhenPushed flag

HidesNavigationBarWhenPushed A library, which adds the ability to hide navigation bar when view controller is pushed via hidesNavigationBarWhenPushed

Danil Gontovnik 55 Oct 19, 2022
A UITextView subclass that adds support for multiline placeholder written in Swift.

KMPlaceholderTextView A UITextView subclass that adds support for multiline placeholder written in Swift. Usage You can set the value of the placehold

Zhouqi Mo 794 Jan 7, 2023
SwiftUI-Margin adds a margin() viewModifier to a SwiftUI view.

SwiftUI-Margin adds a margin() viewModifier to a SwiftUI view. You will be able to layout the margins in a CSS/Flutter-like.

Masaaki Kakimoto(柿本匡章) 2 Jul 14, 2022
Simple battery shaped UIView

BatteryView Simple battery shaped UIView. Usage let batteryView = BatteryView(frame: smallRect) batteryView.level = 42 // anywhere in 0...100 batteryV

Yonat Sharon 50 Sep 19, 2022
Elissa displays a notification on top of a UITabBarItem or any UIView anchor view to reveal additional information.

Elissa Attach a local notification to any UIView to reveal additional user guidance. Usage Example Per default, Elissa will try to align to the center

null 169 Aug 14, 2022
An iOS Library that makes shadows management easy on UIView.

ShadowView is an iOS Shadow library that makes view's shadow implementation easy and sweet ?? ?? . Add simple shadows to add a gaussian blurred projec

Pierre 404 Dec 8, 2022
High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton, Promise and more.

SwiftyUI High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton and more. Features SwiftyView GPU rendering Image and Color

Haoking 336 Nov 26, 2022
Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle.

Twinkle ✨ Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle. This library creates several CAEmitterLayers and animate

patrick piemonte 600 Nov 24, 2022
Custom Beautiful UIView For Handling IDs in iOS

IDView Custom Beautiful UIView For Handling IDs in iOS Setup Set the placeholder images for the front and back faces. override func viewDidLoad()

Omar Labib 6 Aug 21, 2021
A framework which helps you attach observers to `UIView`s to get updates on its frame changes

FrameObserver is a framework that lets you attach observers to any UIView subclass and get notified when its size changes. It doesn't use any Method S

null 11 Jul 25, 2022
Easily use UIKit views in your SwiftUI applications. Create Xcode Previews for UIView elements

SwiftUIKitView Easily use UIKit views in SwiftUI. Convert UIView to SwiftUI View Create Xcode Previews from UIView elements SwiftUI functional updatin

Antoine van der Lee 682 Dec 29, 2022
A swift PropertyWrapper to provide automatic NSView/UIView invalidation when the properties value changes.

A swift PropertyWrapper to provide automatic NSView/UIView invalidation when the properties value changes. It duplicates the @Invalidating propertyWrapper for build targets prior to macOS 12 and iOS 15.

Darren Ford 8 Oct 15, 2021
📹 Framework to Play a Video in the Background of any UIView

SwiftVideoBackground is an easy to use Swift framework that provides the ability to play a video on any UIView. This provides a beautiful UI for login

Wilson Ding 334 Jan 7, 2023
Easily add drop shadows, borders, and round corners to a UIView.

Easily add drop shadows, borders, rounded corners to a UIView. Installation CocoaPods Add the follwing to your Podfile: pod 'Shades' Usage Storyboard

Aaron Sutton 14 Jun 20, 2020
Anchorage - Single file UIView drag and drop system

anchorage Single file UIView drag and drop system anchors.mp4 License Copyright

● ●●   ● 3 Jan 28, 2022
UIView category that adds shake animation

UIView category that adds a shake animation like the password field of the OSX login screen. Screenshot Setup with CocoaPods Add pod 'UIView+Shake' to

Andrea Mazzini 498 Nov 20, 2022
Nice category that adds the ability to set the retry interval, retry count and progressiveness.

If a request timed out, you usually have to call that request again by yourself. AFNetworking+RetryPolicy is an objective-c category that adds the abi

Jakub Truhlář 209 Dec 2, 2022
UITextField category that adds shake animation

UITextField category that adds a shake animation like the password field of the OsX login screen. Screenshot Setup with CocoaPods pod 'UITextField+Sha

Andrea Mazzini 749 Dec 13, 2022
slider view for choosing categories. add any UIView type as category item view. Fully customisable

CategorySliderView Horizontal or vertical slider view for choosing categories. Add any UIView type as category item view. Fully customisable Demo Inst

Cem Olcay 353 Nov 6, 2022
UIView category which makes it easy to create layout constraints in code

FLKAutoLayout FLKAutoLayout is a collection of categories on UIView which makes it easy to setup layout constraints in code. FLKAutoLayout creates sim

Florian Kugler 1.5k Nov 24, 2022