On Mac OS, the coordinate system origin is in the lower left corner!
The following material images are used:
In addition to the NSButton button option, you can also use the NSPopUpButton and NSMenu(menu) on the Mac side.
NSPopUpButton
Set the background color to red for the NSPopUpButton
let speedPopBtn = NSPopUpButton(frame: NSMakeRect (100.0, 100.0, 100.0, 30.0)) self.view.addSubView (speedPopBtn) // Set the background color speedPopbtn. wantsLayer = true speedPopbtn. layer? .backgroundColor = NSColor.red.cgColorCopy the code
Display effect: NSPopUpButton background color in general will not be set!
Initialize the NSPopUpButton instance and add it to the view controller! And set its array (the items it owns)!
let speedPopBtn = NSPopUpButton(frame: NSMakeRect(100.0, 100.0, 100.0, 30.0)) self.view.addSubView (speedPopBtn) Speedpopbtn. pullsDown = false// Set the title of the selected item to false. // Set array (owned items) let typeArr = [" constant speed ", "2x speed "," 4x speed ", "8x speed "," 16x speed "] speedPopbtn. addItems(withTitles: typeArr)Copy the code
Effect: there are “constant speed “,” 2x speed “, “4x speed “,” 8x speed “, “16x speed” these options, you can choose!
Open func removeItem(at index: Int)
Speedpopbtn. removeItem(at: (typearr.count-1))// Remove the last itemCopy the code
Result: Lost the last item “16 times faster”
Add a new item at the end: Open func addItem(withTitle Title: String)
// Add a new item at the end speedPopbtn. addItem(withTitle: "16x ") speedPopbtn. addItem(withTitle:" 32x ")Copy the code
Effect: additional “16 times speed “, “32 times speed “these 2!
Open func insertItem(withTitle title: String, at index: Int)
// SpeedPopbtn. insertItem(withTitle: "1/2 times speed ", at: 0)Copy the code
Effect: the current first item is “1/2 times faster “!
Print an array of NSPopUpButton instances – current entries:
Print (speedPopbtn.itemArray)Copy the code
Print the following: [
,
,
,
,
,
,
,
]
NSPopUpButton selector: open func selectItem(at index: Int)
Speedpopbtn.selectitem (at: 0) // Set the default option -- first: "1/2 times speed "speedPopbtn.selectitem (at: 0)Copy the code
Set the before and after effects of the default selected items:
Set the popup menu location: Open var preferredEdge: NSRectEdge property — the items corresponding to the enumeration (minX/minY/maxX/maxY)
public enum NSRectEdge : UInt {
case minX = 0
case minY = 1
case maxX = 2
case maxY = 3
}
Copy the code
The corresponding effect is shown below:
Add selection response events: Set target and Action!
// Add the response event speedpopbtn. target = self; speedPopBtn.action = #selector(handleSelectPopBtn)Copy the code
Response event when selected:
@objc func handleSelectPopBtn(popBtn : NSPopUpButton) {/ / NSPopUpButton select print (" popBtn. IndexOfSelectedItem: ", popBtn indexOfSelectedItem)}Copy the code
Effect:
You can set up A new custom pop-up menu for the NSPopUpButton: NSMenu instance [A]. Contains menu property (open var menu: NSMenu?) The control of
// Set new custom popup menu let menu = NSMenu(title: "menu ") menu. insertItem(withTitle: "one", Action: nil, keyEquivalent: "", at: 0) // Insert menu. addItem(withTitle: "two", Action: nil, keyEquivalent: "") // Add menu. addItem(withTitle:" "Three ", action: #selector(clickThree), keyEquivalent: "")// add speedPopBtn. Menu = menu;Copy the code
Response event when selecting an item in the custom pop-up menu:
NSPopUpButton @objc func clickThree(item: NSMenuItem; NSMenuItem) { print("clickThree!" , "item.title is",item.title) }Copy the code
The UI effect:
NSPopUpButton (NSPopUpButton, NSMenu, NSPopUpButton, NSMenuItem, NSMenuItem)
GIF: When the “three” item is selected, the item responds only to its own #selector(clickThree) method! So it just prints “clickThree! Item. The title is three “!
NSMenu
NSMenu is used to set up A new custom popup menu for the NSPopUpButton control. Contains menu property (open var menu: NSMenu?) The controls; You can also: [B]. Add NSApp corresponding to the top menu bar menu (mainMenu), [C]. Add status bar menu (NSStatusBar) at the top, [D]. Add Dock menu, [E]. Used as a menu for NSEvent events!
[B]. Add NSApp corresponding to the top of the menu bar menu (mainMenu)
Let mainMenu = nsapp. mainMenu let itemRoot = NSMenuItem(title: "root menu item ", action: #selector(clickMenu), keyEquivalent: "") itemroot. title = "Load_TEXT" "RootMenu- Root directory ")// The text will be displayed as the title of the root directory // The root directory must be set first (layer 1) -- RootMenu, root item -- itemRoot mainMenu? .setsubmenu (rootMenu, for: itemRoot)// add level 1 directory (root directory), you can add level N directory down // add "rootMenu item" at the end //mainMenu? .additem (itemRoot) // Add "root menu item" mainMenu? .insertItem(itemRoot, at: (0 + 2))Copy the code
Procedure: 1. Obtain the main directory of NSApp through nsapp. mainMenu. 2. SetSubmenu Sets the upper root directory (layer 1):NSMenu instance, root directory item :NSMenuItem instance, 3. Insert.addItem or.insertitem into the home directory of NSApp — now you have a new item (” rootmenu.root “) added to the App menu bar menu at the top of the screen!
Effect: The root menu does not pop up when you click select! (Because the next-level menu is not added to the root directory!)
Add level 1 and Level 2 to the root directory (……) Contents and corresponding items:
Let item1 = NSMenuItem(title: "menu 1", Action: #selector: "") item1.target = self; Let item2 = NSMenuItem(title: "Menu ", Action: #selector: "") item2. Target = self; Let item3 = NSMenuItem(title: "menu ", Action: #selector: "") item3. Target = self; rootMenu .addItem(item1) rootMenu .addItem(item2) rootMenu .addItem(item3) let subMenu = NSMenu(title: "Menu3-submenu ") rootmenu.setSubmenu (subMenu, for: item3)// Add secondary directory -- subMenu let item3_1 = NSMenuItem(title: "Menu 3-1", Action: #selector(clickMenu), keyEquivalent: "") item3_1. Target = self let item3_2 = NSMenuItem(title: "Menu 3-2", Action: #selector(clickMenu), keyEquivalent: Submenu.additem (item3_1) submenu.addItem (item3_2) submenu.addItem (item3_2)Copy the code
Method of response when selecting:
@objc func clickMenu(menuItem: NSMenuItem) {
print("App clickMenu", menuItem.title)
}
Copy the code
Effect:
Printing when selecting items:
App clickMenu menu 1 App clickMenu Menu 2 App clickMenu Menu 3 App clickMenu 3-1 App clickMenu 3-2Copy the code
[C]. Add the status bar menu at the top (NSStatusBar)
Let stsItem = nsStatusbar.system.statusItem (withLength:) // Define and add 2 items to the status bar (the status bar will display if the App is enabled) 120)// Self-defined length let img = NSImage(named: "usr_item_email") if #available(macOS 10.14, *) {stsitem.button? .image = img //stsItem.button? .alternateImage = img// Select the image stsitem.button? .imageScaling = NSImageScaling.scaleProportionallyUpOrDown } else { stsItem.image = img //stsItem.alternateImage = Stsitem. isVisible = true let stsItem2 = nsStatusbar.system.statusItem (withLength: NSStatusItem. SquareLength) / / the length of the standard let img2 = NSImage (named: "Usr_Set_Icon ") if #available(macOS 10.14, *) {stsitem2.button? .image = img2 //stsItem.button? . AlternateImage = img2// Select the image stsitem2.button? .imageScaling = NSImageScaling.scaleProportionallyUpOrDown } else { stsItem2.image = img2 //stsItem2.alternateImage = } stsitem2. isVisible = true // At the end: any NSStatusItem must be added to the status bar using the next method (must be called to display the newly added 2 items!) //NSStatusBar .insertValue(stsItem2, inPropertyWithKey: "statusMenu") NSStatusBar .system .insertValue(stsItem2, inPropertyWithKey: "statusMenu")Copy the code
Note: you must add any of the above nsStatusItems to the status bar using either the.insertValue or.system.insertValue method of NSStatusBar at the end — to display the two new items!
Effect: Added 2 items to the status bar (the App will be displayed in the status bar when it is enabled)! The stsItem length is 120 and stsItem2 is the standard length!
Add NSMenu menu to stsItem2:
let statusMenu = NSMenu(title: MinimumWidth = 200 stsitem2.menu = statusMenu statusmenu. insertItem(withTitle: statusMenu) "Selector ", Action: #selector(statusBarItemClickMenu), keyEquivalent: "", at: 0) statusMenu. InsertItem (withTitle: "Customer info ", Action: #selector(statusBarItemClickMenu), keyEquivalent: "", at: 1) statusMenu. InsertItem (withTitle: "User permissions ", Action: #selector(statusBarItemClickMenu), keyEquivalent: "", at: 2) let item3 = statusmenu. items[0+2] as NSMenuItem "Menu3-submenu ") statusmenu.setSubmenu (subMenu, for: item3)// Add subMenu let item3_1 = NSMenuItem(title: "Menu 3-1", Action: #selector(statusBarItemClickMenu), keyEquivalent: Item3_1. Target = self let item3_2 = NSMenuItem(title: "menu 3-2", action: #selector(statusBarItemClickMenu), keyEquivalent: Submenu.additem (item3_1) submenu.addItem (item3_2) submenu.addItem (item3_2)Copy the code
Note: Any operations on status bar items or menus must be called before the.insertValue or.system.insertValue methods of NSStatusBar!
Method of response when selecting:
@objc func statusBarItemClickMenu(menuItem: NSMenuItem) {
print("statusBar Item clickMenu", menuItem.title)
}
Copy the code
Effect:
Printing when selecting items:
StatusBar Item clickMenu Customer profile picture statusBar Item clickMenu Customer information statusBar Item clickMenu Customer permission statusBar Item clickMenu 3-1 StatusBar Item clickMenu 3-2Copy the code
System methods are deprecated before using custom views, choose to add them directly to the. Button of the NSMenuItem item
// let sts_w = stsitem2.button? .frame.size.width let sts_h = stsItem2.button?.frame.size.height let customerV = NSView(frame: NSMakeRect(0, 0, sts_w! , sts_h!) ) customerV.wantsLayer = true customerV.layer? BackgroundColor = nscolor.red. CgColor // stsitem2. view = customerV// There is A problem: A. B. warning -- 'view' was deprecated in macOS 10.14: Use the standard button property instead stsitem2.button? .addSubview(customerV)Copy the code
Effect:
Note: This operation must also be called before the.insertValue or.system.insertValue methods of the NSStatusBar!
Final code: call the.insertValue or.system.insertValue method of NSStatusBar, must be at the end!
[D]. Add Dock menu
NSApplication “- (nullable NSMenu *)applicationDockMenu:(NSApplication *) Sender;” Methods! Func applicationDockMenu(_ sender: NSApplication) -> NSMenu? !
Do not use: a. do not expose and write it; b. set return to nil(as follows).
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
return nil
}
Copy the code
Effect of execution:
When the func applicationDockMenu(_ Sender: NSApplication) -> NSMenu? Method: Add some ‘dockMenu’ items!
Let dockMenu = NSMenu(title: "dockMenu") let item1 = NSMenuItem(title: "menu 1", Action: #selector(clickDockMenu), keyEquivalent: "") item1.target = self; Let item2 = NSMenuItem(title: "Menu ", Action: #selector: "") item2. Target = self; Let item3 = NSMenuItem(title: "clickDockMenu ", Action: #selector: "") item3. dockMenu .addItem(item1) dockMenu .addItem(item2) dockMenu .addItem(item3) let subMenu = NSMenu(title: "Menu ") let item3_1 = NSMenuItem(title: "menu 3-1", Action: #selector(clickDockMenu), keyEquivalent: "") item3_1. Target = self let item3_2 = NSMenuItem(title: "", Action: #selector(clickDockMenu), keyEquivalent: "") item3_2.target = self subMenu .addItem(item3_1) subMenu .addItem(item3_2) dockMenu .setSubmenu(subMenu, for: Item3)// Select * from item3, select * from item3, select * from item3Copy the code
Display effect:
Printing when selecting:
DockMenu clickMenu 1 dockMenu clickMenu 2 dockMenu clickMenu 3-1 dockMenu clickMenu 3-2Copy the code
Effect when selecting: “Menu 3″ is invalid, but can be clicked on” menu 3-1″, “menu 3-2”
Dock menu: when a sub-menu is added for a certain item, select this item will not respond to the corresponding event, but select the sub-item will respond to the corresponding event!
[E]. Used as a menu for NSEvent events!
When an NSEvent event occurs, you can use the following method to create a pop-up menu after passing the NSEvent event!
open class func popUpContextMenu(_ menu: NSMenu, with event: NSEvent, for view: NSView)
open class func popUpContextMenu(_ menu: NSMenu, with event: NSEvent, for view: NSView, with font: NSFont?)
Copy the code
To get an NSEvent event, I’m using the right mouse button for example, and I need to override the NSApplication – (void)rightMouseDown:(NSEvent *)event; Override func rightMouseDown(with event: NSEvent) {}
Let menuForUsr = NSMenu(title: "edit user ") let item1 = NSMenuItem(title:" set avatar "), action: nil, keyEquivalent: "") let item2 = NSMenuItem(title: "NSMenuItem ", action: nil, keyEquivalent: "") let item3 = NSMenuItem(title:" NSMenuItem ", action: nil, keyEquivalent: "") let item3 = NSMenuItem(title: } // For item3, let permissionMenu = NSMenu(title: Let item3_2 = NSMenuItem(title: NSMenuItem, action: nil, keyEquivalent: "") let item3_2 = NSMenuItem(title: NSMenuItem) "Dialogue permissions ", Action: nil, keyEquivalent: "") permissionMenu .addItem(item3_1) permissionMenu .addItem(item3_2) item3.submenu = permissionMenu let item4 = NSMenuItem(title: "Show online ", Action: nil, keyEquivalent: "") // If.onStateImage,.offStateImage exceeds size, the font will be overwrite! And. Image size beyond the size will be displayed according to the size of the picture! item4.onStateImage = NSImage(named: "usr_item_sel") item4.offStateImage = NSImage(named: "Usr_item_nor ") let item5 = NSMenuItem(title:" customer mail message ", Action: nil, keyEquivalent: "") item5.image = NSImage(named: "Usr_item_email ")//. Image with title menuforus.insertitem (item1, at: Menuforusr. addItem(item2) menuforusr. insertItem(item3, at: (0+2)) menuForUsr .addItem(item4) menuForUsr .addItem(item5) menuForUsr.showsStateColumn = true / / menuForUsr. SetAccessibilityFrame (NSMakeRect (0, 0, 200, 200)) / / / / invalid no matter which view (this view is in the Window), NSMenu. PopUpContextMenu (menuForUsr, with: event, for: self.view)// Displays the NSMenu menuCopy the code
Effect: None of the items are selectable because no action is configured for the item (action is nil)! When. OnStateImage and. OffStateImage are out of size, the font will be overwritten! And. Image size beyond the size will be displayed according to the size of the picture!
Optimization: A. Action must be set for this item to respond to events! B. When setting pictures, you must set the corresponding size for picture display! (.onStateImage? The size, offStateImage? The size, the image? .size)
Add the global variable needShowOnline to record whether or not to “show online”
Public var needShowOnline = falseCopy the code
Override func rightMouseDown(with event: NSEvent) {}
Let menuForUsr = NSMenu(title: "edit user ") let item1 = NSMenuItem(title:" set avatar ", action: #selector(setUpIcon), keyEquivalent: "") let item2 = NSMenuItem(title: ""), action: #selector(setUpBaseInfo), keyEquivalent: "") let item3 = NSMenuItem(name: "", action: # the selector (setUpPermissionLevelApply), keyEquivalent: "") / / setup submenu and corresponding options let permissionMenu = NSMenu (title: "Access level application") let item3_1 = NSMenuItem (title: "pay permissions", the action: # selector (setUpPermissionLevelApply), keyEquivalent: "") let item3_2 = NSMenuItem (title:" dialogue permissions ", the action: # selector (setUpPermissionLevelApply), keyEquivalent: "") permissionMenu .addItem(item3_1) permissionMenu .addItem(item3_2) item3.submenu = permissionMenu let item4 = NSMenuItem(title: "display online status ", Action: #selector(setUpShowOnline), keyEquivalent: "") item4.onStateImage = NSImage(named: "Usr_item_sel ") item4.offStateImage = NSImage(named:" usr_ITEM_nor ") // If onStateImage and offStateImage exceed the size, the font will be overwritten. The size of the image will be displayed in accordance with the size of the image! Let img_W: CGFloat = 15.0 item4.onstateImage? .size = NSMakeSize(img_W, img_W) item4.offStateImage? .size = NSMakeSize(img_W, img_W) item4.state = (needShowOnline == true ? Nscontrol.statevalue. On: nscontrol.statevalue. Off) let item5 = NSMenuItem(title: "Customer email message ", action: #selector(showEmailInfos), keyEquivalent: "") item5.image = NSImage(named: "Usr_item_email ")// with the title // Will squeeze the font when the image size exceeds! item5.image? .size = NSMakeSize(img_W, img_W) //item5.image? .size = NSMakeSize(img_W+50, img_W+50) menuForUsr .insertItem(item1, at: Menuforusr. addItem(item2) menuforusr. insertItem(item3, at: (0+2)) menuForUsr .addItem(item4) menuForUsr .addItem(item5) menuForUsr.showsStateColumn = true / / menuForUsr. SetAccessibilityFrame (NSMakeRect (0, 0, 200, 200)) / / / / invalid no matter which view (this view is in the Window), NSMenu. PopUpContextMenu (menuForUsr, with: event, for: self.view)// Displays the NSMenu menuCopy the code
The response events selected by each NSMenuItem:
@objc func setUpIcon(item: NSMenuItem) { print("setUpIcon", "item.title:\(item.title)") } @objc func setUpPermissionLevelApply(item: NSMenuItem) { print("setUpPermissionLevelApply", "item.title:\(item.title)") } @objc func setUpBaseInfo(item: NSMenuItem) { print("setUpBaseInfo", "item.title:\(item.title)") } @objc func setUpShowOnline(item: NSMenuItem) { needShowOnline = ! needShowOnline print("setUpShowOnline", "item.title:\(item.title)", "needShowOnline:\(needShowOnline)") } @objc func showEmailInfos(item: NSMenuItem) { print("showEmailInfos", "item.title:\(item.title)") }Copy the code
Effect: Picture size normal! All items are optional, respond to the corresponding event! When you select the “ShowOnline” TAB, needShowOnline will display either a normal state image (offStateImage) or a selected state image (onStateImage) based on the state of needShowOnline!
Tips: When a certain item is needed, it cannot be selected!
Example: Make the “Permission level request” item unselectable!
If it was OC, it would have been implemented directly with the following code:
item3.enabled = NO; [item3.menu setAutoenablesItems:NO]; / / pointsCopy the code
Item3. isEnabled = false, item3.menu? . AutoenablesItems = false, item3. SetAccessibilityEnabled (false), item3. The menu? .setAccessibilityEnabled(false)
It turns out that if you set an item’s **action to nil, the item can’t be selected **! This is encapsulated as follows: Use the title of the item to set the corresponding action (you can also use keyEquivalent)!
func setItemEnable(item: NSMenuItem, enable :Bool) { //var actionUse: Selector? = #selector(setUpIcon) var actionUse = #selector(setUpIcon) switch item.title { ActionUse = #selector(setUpIcon) case "Basic information setting ": actionUse = #selector(setUpBaseInfo) case" Permission level application ": ActionUse = # selector (setUpPermissionLevelApply) case "to show online status" : actionUse = # selector (setUpShowOnline) case "customer mail messages" : actionUse = #selector(showEmailInfos) default: break } if enable { item.action = actionUse } else { item.action = nil } }Copy the code
Call as follows:
Self. setItemEnable(item: item3, enable: false)Copy the code
Effect: “Permission level request” item cannot be selected!
The NSMenu menu pops up only in response to a mouse event for a control |
---|
Add global variable: a picture of an avatar
var usrImgV: NSImageView? = nil
Copy the code
Put it in view Controller:
usrImgV = NSImageView(frame: NSMakeRect(50, 50, 100, 100)) self.view .addSubview(usrImgV!) usrImgV! .image = NSImage(named: "usr_Set_Icon") usrImgV! .tooltip = "User Settings"Copy the code
Effect:
Use any of the following codes to pop up the NSMenu menu (regardless of which view (NSView()/self.view/ self.usrimgv!) On, the NSMenu menu pops up)!
-
Use NSView() to create a view that is not in the Window
Nsmenu. popUpContextMenu(menuForUsr, with: event, for: NSView())// Use 'view not in Window' to pop up menus - but none of them are selectable!Copy the code
Effect: the right mouse button will pop up under the NSMenu menu, each can not be selected!
-
Using the self. The view
NSMenu. PopUpContextMenu (menuForUsr, with: event, for: self.view)// Displays the NSMenu menuCopy the code
Effect: the right mouse button will pop up under the NSMenu menu, options are optional!
-
Using the self usrImgV!
NSMenu .popUpContextMenu(menuForUsr, with: event, for: self.usrImgV!) Copy the code
Effect: the right mouse button will pop up under the NSMenu menu, options are optional!
Conclusion: With ‘View in Window’, popup menu options are optional! , use ‘view not in Window’, popup menu each item is not selectable!
PopUpContextMenu cannot be used to “pop up the NSMenu menu only in response to the mouse event of a control”.
Implementation “only respond to A control mouse event, will pop up the NSMenu menu” function: A. Override func rightMouseDown(with event: NSEvent) {} override func rightMouseDown(with event: NSEvent) {} Then calculate the size and position of the usrImgV relative to the Window and determine whether the (NSPoint) point is within the icon (usrImgV) range (x:50 to (100+50),y:50 to (100+50))!
This approach only works when the view hierarchy is simple! The amount of computation can be scary when the view hierarchy is multifaceted!! 😳
B. Define a view class that declares a closure for value passing (this closure passes the view’s NSEvent event to the view controller)! Override func rightMouseUp(with event: NSEvent) {} ¶ Override func rightMouseUp(with event: NSEvent) {} ¶ override func rightMouseUp(with event: NSEvent) {} ¶ Override func rightMouseUp(with event: If (NSEvent) {} “is used to get the location of the click relative to the Window, it doesn’t matter where (NSPoint) is.
Here is a custom image class UsrImgV:
The code in the “usrimgv.swift” file:
Import Cocoa Public TypeAlias rightMouseUpClosure = (_ event: NSEvent) -> closure = (_ event: NSEvent) -> () NSImageView { var rightMouseUpBlock : rightMouseUpClosure? Override func rightMouseUp(with event: NSEvent) {let locPt = event. LocationInWindow print("UsrImgV point location: ",locPt) // We can only get the location information relative to the Window, so it doesn't matter where we get it! rightMouseUpBlock? Deinit {print("UsrImgV deinit") rightMouseUpBlock = nil} Override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } }Copy the code
In ViewController, change the global variable usrImgV from NSImageView to usrImgV! will
var usrImgV: NSImageView? = nil Copy the code
Change for
var usrImgV: UsrImgV? = nil Copy the code
Initializing the UsrImgV instance and related configurations:
usrImgV = UsrImgV(frame: NSMakeRect(50, 50, 100, 100)) self.view .addSubview(usrImgV!) usrImgV! .image = NSImage(named: "usr_Set_Icon") usrImgV! .tooltip = "User Settings" usrImgV! .rightMouseUpBlock = { [self] (event: NSEvent) -> () in let locPt = event .locationInWindow print("usrImgV! .rightMouseupBlock Point location: ",locPt)// Prints the NSPoint message self. createMenuForUser(with: event)}// Closure callback -- handles the NSEvent eventCopy the code
Func createMenuForUser(with event: NSEvent) {}
Func createMenuForUser(with event: NSEvent) {let menuForUsr = NSMenu(title: "edit user ") let item1 = NSMenuItem(title: "Set avatar ", action: #selector(setUpIcon), keyEquivalent: "") let item2 = NSMenuItem(title:" set avatar ", action: #selector(setUpBaseInfo), keyEquivalent: "") let item3 = NSMenuItem(name: "", action: # the selector (setUpPermissionLevelApply), keyEquivalent: "") / / setup submenu and corresponding options let permissionMenu = NSMenu (title: "Access level application") let item3_1 = NSMenuItem (title: "pay permissions", the action: # selector (setUpPermissionLevelApply), keyEquivalent: "") let item3_2 = NSMenuItem (title:" dialogue permissions ", the action: # selector (setUpPermissionLevelApply), keyEquivalent: "") permissionMenu .addItem(item3_1) permissionMenu .addItem(item3_2) item3.submenu = permissionMenu let item4 = NSMenuItem(title: "display online status ", Action: #selector(setUpShowOnline), keyEquivalent: "") item4.onStateImage = NSImage(named: "Usr_item_sel ") item4.offStateImage = NSImage(named:" usr_ITEM_nor ") // If onStateImage and offStateImage exceed the size, the font will be overwritten. The size of the image will be displayed in accordance with the size of the image! Let img_W: CGFloat = 15.0 item4.onstateImage? .size = NSMakeSize(img_W, img_W) item4.offStateImage? .size = NSMakeSize(img_W, img_W) item4.state = (needShowOnline == true ? Nscontrol.statevalue. On: nscontrol.statevalue. Off) let item5 = NSMenuItem(title: "Customer email message ", action: #selector(showEmailInfos), keyEquivalent: "") item5.image = NSImage(named: "Usr_item_email ")// with the title // Will squeeze the font when the image size exceeds! item5.image? .size = NSMakeSize(img_W, img_W) //item5.image? .size = NSMakeSize(img_W+50, img_W+50) menuForUsr .insertItem(item1, at: Menuforusr. addItem(item2) menuforusr. insertItem(item3, at: (0+2)) menuForUsr .addItem(item4) menuForUsr .addItem(item5) menuForUsr.showsStateColumn = true / / menuForUsr. SetAccessibilityFrame (NSMakeRect (0, 0, 200, 200)) / / / / invalid no matter which view (this view is in the Window), // nsmenu. popUpContextMenu(menuForUsr, with: event, for: NSMenu. PopUpContextMenu (menuForUsr, with: event, for: self.view)Copy the code
Effect:
- in
usrImgV
When the right mouse button is pressed, UsrImgV classfunc rightMouseUp(with event: NSEvent)
Method, ViewContoller classfunc rightMouseUp(with event: NSEvent)
Methods all call back (both print fetch (NSPoint)pointtheinformation-“Point the location:“And”UsrImgV point location:“)! Menu options are optional, respond to the corresponding event! At this point inIn the ViewContollerThe * *usrImgV! .rightMouseUpBlock
closureSome haveCallback **, with returnedNSEvent eventcreateNSMenu menu! - in
self.view
In (and inusrImgV
When the right mouse button is pressed, it is only ViewContoller classfunc rightMouseUp(with event: NSEvent)
The method calls back (prints the fetch (NSPoint)pointtheinformation-“Point the location:“)!
Before the Mac side of the code is OC to write, now look at the feeling is very complicated. 😂 write as Swift as possible after it
goyohol’s essay