UIMenuItem with image and closure(block) action

Related tags

Menu MenuItemKit
Overview

MenuItemKit

MenuItemKit provides image and block(closure) support for UIMenuItem.

MenuItemKit is a Swift project but Objective-C is supported without any doubt.

Screenshot

Install

Swift Package

Add this repo URL to your Swift package dependencies.

CocoaPods

pod 'MenuItemKit', '~> 4.0.0'

Xcode subproject

  1. Add the MenuItemKit repository as a submodule of your application’s repository.
  2. Drag and drop MenuItemKit.xcodeproj into your application’s Xcode project or workspace.
  3. On the “General” tab of your application target’s settings, add MenuItemKit.framework to the “Embedded Binaries” section.

If you would prefer to use Carthage, please pull request.

How to use

MenuItemKit is very easy to adopt, it provides only 2 APIs:

typealias MenuItemAction = (UIMenuItem) -> ()

extension UIMenuItem {
    convenience init(title: String, image: UIImage?, action: MenuItemAction)
    convenience init(title: String, action: MenuItemAction)
}

For Objective-C, MenuItemKit provides prefixed API names for safe reasons:

@interface UIMenuItem (SWIFT_EXTENSION(MenuItemKit))
- (nonnull instancetype)mik_initWithTitle:(NSString * _Nonnull)title image:(UIImage * _Nullable)image action:(MenuItemAction _Nonnull)action;
- (nonnull instancetype)mik_initWithTitle:(NSString * _Nonnull)title action:(MenuItemAction _Nonnull)action;
@end

Just init UIMenuItems with above APIs, and set them to menuItems of UIMenuItemController. MenuItemKit will take care of the rest parts, you don't need to add any code related to responder chain in your view or view controller.

Check dome projects (both Swift and Objective-C are provided) for more details.

Advance Usage

For menu items out of your control, you can use static func installTo(responder: UIResponder, shouldShowForAction: @escaping (Selector, Bool) -> Bool = default) to configure items visibility. Check AutoPopupMenuControllerDemo.

About Me

  • Twitter: @_cxa
  • Apps available in App Store: http://lazyapps.com
  • PayPal: xianan.chen+paypal 📧 gmail.com, buy me a cup of coffee if you find it's useful for you, thanks.

License

MenuItemKit is released under the MIT license. In short, it's royalty-free but you must keep the copyright notice in your code or software distribution.

Comments
  • Crash when run it without connecting to Xcode

    Crash when run it without connecting to Xcode

    in Swizzlings.m
    
    + (void)load
    {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
        for (id klass in @[[UIMenuController class], [UILabel class], [NSString class]]) {
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
          [klass performSelector:NSSelectorFromString(@"_mik_load")]; // <---- crash if this line is not comment out
    #pragma clang diagnostic pop
        }
      });
    }
    
    opened by magicboker 14
  • canPerformAction Method not getting called for custom selectors

    canPerformAction Method not getting called for custom selectors

    Hi Following is the way i am creating custom MenuItems

    let menuController = UIMenuController.shared let redImageItem = UIMenuItem(title: Highlight.redColor.rawValue, image: imageWithColor(Highlight.redColor.getColor())!) { [weak self] (item) in self?.setRedColor() }

    But when i log all the actions in canPerformAction method, i cant find one for this Menu Item. How can i check this?

    opened by saleelkarkhanis 9
  • Problem with MenuItemAction vs. Selectors

    Problem with MenuItemAction vs. Selectors

    I'm working on a fork of FolioReaderKit and your library is used there.

    As a way of "filtering" which actions will be displayed on each scenario it was chosen to override the function canPerformAction of the UIWebView. There they verify each action (which is a Selector) and see if the item will end up displaying on the screen.

    Like this:

    open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(highlight(_:))
            || action == #selector(createAnnotation(_:))
            || (action == #selector(define(_:)) && isOneWord)
            || (action == #selector(play(_:)) && (book.hasAudio() || readerConfig.enableTTS))
            || (action == #selector(share(_:)) && readerConfig.allowSharing)
            || action == #selector(copyText(_:)) {
            return true
        } else {
            return false
        }
    }
    

    The thing is that most of those actions are actually a Selector and were created using the default API like this:

    let highlightItem = UIMenuItem(title: readerConfig.localizedHighlightMenu, action: #selector(highlight(_:)))
    

    When using your API for creating items with images we end up sending MenuItemAction instead of Selectors:

    let discussion = UIImage(readerImageNamed: "discussion-marker")
    let discussionItem = UIMenuItem(title: "D", image: discussion!) { [weak self] _ in   
        self?.createHighlight()
    }
    

    Thus it's very hard to work combined with canPerformAction (which has a Selector as parameter)

    Any suggestions of filtering which UIMenuItem(created with images, using MenuItemAction) will appear on a specific scenario?

    enhancement 
    opened by danfsd 8
  • IOS 10 - All the coloured images are became white

    IOS 10 - All the coloured images are became white

    Hi, I've tested my app in iOS 10 beta and found that the menu items became white:

    Before:

    2118de68-3d64-11e6-9fb5-81bc121ecbeb

    And now with iOS 10 this look like the following:

    3af3c528-3d64-11e6-81cf-e222572e3a68

    Thanks in advance

    opened by shahaf 8
  • Images getting cropped out

    Images getting cropped out

    Hello, thank you for this great kit, i have used the sample code in the demo. It works for me but there is just one issue, the images get cut out at the bottom and top. I have tried adding padding to the image height itself, but it doesn't make the menu taller. Is there any way to make the menu height bigger to fit the whole image? Thank you.

    opened by WeiMin-M 4
  • Unable to get image menu in case of wkwebview

    Unable to get image menu in case of wkwebview

    Hi I initialized custom menu on view did load with a controller having wkwebview. I am unable to add up these custom menus although I am able to see the default type UIMenuItem say I add up "ABC" Help

    opened by devanshu2 4
  • error on call `installTo` servalTimes

    error on call `installTo` servalTimes

    if call the installTo servalTimes, you will find self which was catched by block still the same one. And I found that, the installTo was hooked once. It made that if you call the installTo servalTimes, the action wouldn't be invoked at all.

    opened by starFelix 3
  • CocoaPods Owner

    CocoaPods Owner

    Hey Chen,

    I've implemented CocoaPods support, but I had to set myself as the owner. That's obviously not fair, since you're the owner, so if you could, please follow these steps to set yourself as the owner of the pod 😊

    https://guides.cocoapods.org/making/getting-setup-with-trunk.html#adding-other-people-as-contributors

    I will add CocoaPods/Carthage support to the README soon.

    opened by alexpopov 3
  •  select all, copy, paste text menu gets added when textfield is first responder and menu tapped.

    select all, copy, paste text menu gets added when textfield is first responder and menu tapped.

    When using, if text field is tapped then, the other options like select all, copy, paste text menu gets added in the menu and my added options moves to right with arrow option. How to disable those options to not add in menu?

    screen shot 2018-04-20 at 7 17 26 pm
    opened by PrakashMaharjan 2
  • Crash: Unrecognized selector sent to instance for custom action

    Crash: Unrecognized selector sent to instance for custom action

    Hello. I;'m trying to use this great kit for my custom menu actions, but unfortunately if I add the actions and do not show the menu on a particular button click, My app crashes when any custom action is pressed with the following exception:

    -[UITextView _menuitemkit_block_6BB2EFBD_033E_4144_9AF4_1D7FB291ED08:]: unrecognized selector sent to instance 0x7fbdc5079600

    I'm trying to add some functions to a TextView's popup menu (not a menu I set visible by hand), so in my VC's viedDidload I do the following:

    func setupEditMenu() {
    	let controller = UIMenuController.shared
    
    	controller.arrowDirection = .default
    	controller.setTargetRect(articleView.bodyTextView.frame, in: self.view)
    
    	let action: MenuItemAction = { [weak self] menuItem in
    		self?.highlightTapped( (menuItem.title as NSString).integerValue) 
            }
    
    	let yellow = UIMenuItem(title: "1", image: #imageLiteral(resourceName: "hl_yellow"), action: action)
    	let orange = UIMenuItem(title: "2", image: #imageLiteral(resourceName: "hl_orange"), action: action)
    	let green = UIMenuItem(title: "3", image: #imageLiteral(resourceName: "hl_green"), action: action)
    	let pink = UIMenuItem(title: "4", image: #imageLiteral(resourceName: "hl_pink"), action: action)
    	let blue = UIMenuItem(title: "5", image: #imageLiteral(resourceName: "hl_blue"), action: action)
    
    	controller.menuItems = [yellow, orange, green, pink, blue]
    	controller.update()
    }
    
    

    and when one of the above actions gets selected I get the exception above. However, if I call setupEditMenu when a button is pressed, all the actions work fine, even when the menu is presented by the TextView.

    highlightTapped is a function below that gets an int value and highlights my text depending on that value.

    I'm assuming this is a bug on UIMenuKit and how the selectors are generated for each action. Any Idea why this is happening and how to fix it or a workaround. I want the menu to be presented automatically when the user selects text inside the TextView, not when a button is pressed.

    Any help will be greatly appreciated. Thank you very much!

    opened by lpbas 2
  • Not able to add menu item with Image for Webview

    Not able to add menu item with Image for Webview

    I am trying ti add Image as UIMenuItem for my Webview using this library. this works well when i use xcode 8.x but it fails when i use Xcode 9.0 and application hangs.

    Any help?

    opened by saleelkarkhanis 2
Releases(4.0.1)
Owner
Realazy Xian-an CHEN
Indie iOS app developer.
Realazy Xian-an CHEN
Library provides easy to implement variation of Android (Material Design) Floating Action Button for iOS. You can use it as your app small side menu. 🌶

RHSideButtons ?? Library provides easy to implement variation of Android (Material Design) Floating Action Button for iOS. You can use it as your app

Robert Herdzik 166 Nov 14, 2022
Easy-to-use action menu

About Navigate Features Installation Usage Delegate Features Highly customizable support dark/light theme corner radius blured background width (iPad)

Vlad Karlugin 4 Jan 6, 2023
Swipable tab and menu View and ViewController.

SwipeMenuViewController Overview SwipeMenuViewController provides SwipeMenuView and SwipeMenuViewController. This is very useful to build swipe-based

Yusuke Morishita 1.2k Dec 29, 2022
SwiftySideMenu is a lightweight and easy to use side menu controller to add left menu and center view controllers with scale animation based on Pop framework.

SwiftySideMenu SwiftySideMenu is a lightweight, fully customizable, and easy to use controller to add left menu and center view controllers with scale

Hossam Ghareeb 84 Feb 4, 2022
⭕️ CircleMenu is a simple, elegant UI menu with a circular layout and material design animations. Swift UI library made by @Ramotion

CIRCLE MENU Simple, elegant UI menu with a circular layout and material design animations We specialize in the designing and coding of custom UI for M

Ramotion 3.4k Dec 29, 2022
Interactive view transition to display menus with flowing and bouncing effects in Swift

FlowingMenu FlowingMenu provides an interactive transition manager to display menu with a flowing and bouncing effects. The Objective-C countepart is

Yannick Loriot 975 Dec 21, 2022
An easy to use and setup floating view for your app. 🎡

HHFloatingView An easy to use and setup floating view for your app. ?? Installation Manually - Add HHFloatingView/Source folder to your Project. And y

Hemang 95 Dec 15, 2022
PagingKit provides customizable menu UI. It has more flexible layout and design than the other libraries.

PagingKit provides customizable menu & content UI. It has more flexible layout and design than the other libraries. What's this? There are many librar

Kazuhiro Hayashi 1.3k Jan 9, 2023
Grid and Circular Menu for iOS.

IGCMenu IGCMenu library gives easy way to create Grid and Circular menu in app. This is light weight and highly customisable menu.Support iOS 7 and ab

Sunil Sharma 138 Nov 14, 2022
An iOS drop down menu with pretty animation and easy to customize.

IGLDropDownMenu An iOS drop down menu with pretty animation. Screenshot How To Use Use CocoaPods: pod 'IGLDropDownMenu' Manual Install: Just drap the

Galvin Li 1.2k Dec 27, 2022
Hamburger Menu using Swift and iOS 8 API's

FrostedSidebar Hamburger Menu using Swift and iOS 8 API's Heavily influenced by @_ryannystrom's RNFrostedSidebar This implementation uses iOS 8's new

Evan Dekhayser 429 Oct 21, 2022
UIKit drop down menu, simple yet flexible and written in Swift

DropDownMenuKit DropDownMenuKit is a custom UIKit control to show a menu attached to the navigation bar or toolbar. The menu appears with a sliding an

Quentin Mathé 258 Dec 27, 2022
Menu controller with expandable item groups, custom position and appearance animation written with Swift. Similar to ActionSheet style of UIAlertController.

Easy to implement controller with expanding menu items. Design is very similar to iOS native ActionSheet presentation style of a UIAlertController. As

Anatoliy Voropay 22 Dec 27, 2022
Simple and Elegant Drop down menu for iOS 🔥💥

SwiftyMenu is simple yet powerfull drop down menu component for iOS. It allow you to have drop down menu that doesn't appear over your views, which gi

Karim Ebrahem 502 Nov 29, 2022
Describing a bug with Sheet and Menu

MenuTest Describing a bug with Sheet and Menu This repository is related to a question in Apples developers forum, with id: 692338 Dismiss via Button

Tim 0 Oct 14, 2021
Barber lives in your macOS menu bar and keeps track of what needs to be updated.

Barber Barber is a macOS application to keep track of application updates easily. It lives in your menu bar, and uses homebrew to determine what's out

Max Ainatchi 1 Nov 30, 2021
Control your display's brightness from the macOS menu bar. Simple and easy to use.

MonitorControl Lite Control your display's brightness from the macOS menu bar. Simple and easy to use. About MonitorControl Lite is a simplified versi

null 62 Dec 11, 2022
Simple example of view that appears on tap button and dismiss with swipe gesture.

MenuWithSlide Simple SwiftUI example of how to show side menu with slide effect. On button press - appeares, on background tap or swipe right - dissmi

Evgeny 1 Nov 29, 2021
Alejandro Piguave 24 Dec 30, 2022