具有自定义视图的 NSMenuItem 在滚动时消失

Posted

技术标签:

【中文标题】具有自定义视图的 NSMenuItem 在滚动时消失【英文标题】:NSMenuItem with custom view disappears while scrolling 【发布时间】:2021-01-12 16:58:35 【问题描述】:

我用 NSMenuItem 实现了一个 NSMenu 并为其设置了自定义视图。当菜单可滚动时,鼠标悬停在 ▼ 按钮上滚动会导致某些 menuItem 消失(或无法正确绘制)。希望有人给我一些帮助。我会很感激的。

以下是有关此问题的视频: https://streamable.com/obrbon

这是我的代码:

private func setupMenuItemView(_ menu: NSMenu) 
    let menuItemHeight: CGFloat = 20
    let menuWidth = frame.width
    let textFieldPadding: CGFloat = 10
    for menuItem in menu.items 
        guard !menuItem.title.isEmpty else  continue 
        let menuItemView = MenuItemView(frame: NSRect(x: 0, y: 0, width: Int(menuWidth), height: menuItemHeight))
        let textField = MenuItemTextField(labelWithString: menuItem.title)
        textField.frame = NSRect(
            x: textFieldPadding,
            y: (menuItemView.frame.height-textField.frame.height)/2,
            width: menuWidth-textFieldPadding*2,
            height: textField.frame.height
        )
        textField.lineBreakMode = .byTruncatingTail
        menuItemView.addSubview(textField)
        menuItemView.toolTip = menuItem.title
        menuItem.view = menuItemView
        menuItem.target = self
        menuItem.action = #selector(onMenuItemClicked(_:))
    


fileprivate class MenuItemView: NSView 
    override func mouseUp(with event: NSEvent) 
        guard let menuItem = enclosingMenuItem else  return 
        guard let action = menuItem.action else  return 
        NSApp.sendAction(action, to: menuItem.target, from: menuItem)
        menuItem.menu?.cancelTracking()
    

    override func draw(_ dirtyRect: NSRect) 
        guard let menuItem = enclosingMenuItem else  return 
        if menuItem.isHighlighted 
            NSColor.alternateSelectedControlColor.set()
         else 
            NSColor.clear.set()
        
        NSBezierPath.fill(dirtyRect)
        super.draw(dirtyRect)
    


fileprivate class MenuItemTextField: NSTextField 
    override var allowsVibrancy: Bool 
        return false
    

拨打setupMenuItemView() 后,我拨打menu.popup()。 希望这些信息对您有所帮助。

【问题讨论】:

您确定您的代码实现正确吗?调试项目似乎一次又一次地创建 编辑您的问题并发布您的代码。看看如何提供minimal reproducible example 抱歉,刚刚忘记发布我的代码。我编辑并发布了我的代码。希望对您有所帮助。 请发minimal reproducible example。 使用带有文本字段的 NSView 创建菜单有什么好处?使用 pullDown 选项将菜单添加到 NSPopUpButton 或使用 PopUpContextMenu 会更容易吗? 【参考方案1】:

我无法让您发布的代码正常工作。下面的演示是一个替代方案,它使用一个 popUpContextual 菜单,其中嵌入了 menuItem 视图中的子类文本字段(请注意,使用与每个 menuItem 关联的视图并且不创建自定义视图类)。文本对齐和截断功能。菜单宽度也很灵活,可以设置为匹配菜单标题字段的宽度。该演示可以在 Xcode 中运行,方法是将源代码复制/粘贴到新添加的“main.swift”文件中,并另外删除 Apple 的 AppDelegate 类。

import Cocoa

var view = [NSTextField]()

class TextField: NSTextField 

override func mouseDown(with event: NSEvent) 
 print("selected = \(self.tag)")
 for i:Int in 0..<view.count 
  if(self.tag == i) 
   view[i].backgroundColor = .lightGray
    else 
   view[i].backgroundColor = .clear
  
 




class AppDelegate: NSObject, NSApplicationDelegate 
var window:NSWindow!
var menu = NSMenu()

let _menuLeft : CGFloat = 40
let _menuTop : CGFloat = 70
let _menuWidth : CGFloat = 70
let _menuItemH : CGFloat = 20

@objc func menuBtnAction(_ sender:AnyObject )  
let menuOrigin = NSMakePoint(_menuLeft, sender.frame.origin.y - 5)
let wNum : Int = sender.window.windowNumber
let event  = NSEvent.mouseEvent(with:.leftMouseDown, location:menuOrigin, modifierFlags:[], timestamp:0, windowNumber:wNum, context:nil, eventNumber:0, clickCount:1, pressure:1.0)
NSMenu.popUpContextMenu(menu, with: event!, for: window.contentView!)


func buildMenu() 
 let mainMenu = NSMenu()
 NSApp.mainMenu = mainMenu
 // **** App menu **** //
 let appMenuItem = NSMenuItem()
 mainMenu.addItem(appMenuItem)
 let appMenu = NSMenu()
 appMenuItem.submenu = appMenu
 appMenu.addItem(withTitle: "Quit", action:#selector(NSApplication.terminate), keyEquivalent: "q") 

    
func buildWnd() 
    
let _wndW : CGFloat = 400
let _wndH : CGFloat = 300

 window = NSWindow(contentRect:NSMakeRect(0,0,_wndW,_wndH),styleMask:[.titled, .closable, .miniaturizable, .resizable], backing:.buffered, defer:false)
 window.center()
 window.title = "Swift Test Window"
 window.makeKeyAndOrderFront(window)

let menuItems = ["10%","25%","50%","75%","100%","Longer text."]
menu.title = "Fit"
var count:Int = 0
for mItem in menuItems
 let menuItem = NSMenuItem()
 menu.addItem(menuItem)
 let textField = TextField(frame:NSMakeRect(0,0,_menuWidth, _menuItemH))
 menuItem.view = textField
 textField.alignment = .left // .left, .center, .right
 textField.stringValue = mItem
 textField.lineBreakMode = .byTruncatingTail
 textField.backgroundColor = .clear
 textField.isEditable = false
 textField.tag = count
 textField.isBordered = false
 textField.font = NSFont( name:"Menlo bold", size:14 )
 count = count + 1
 view.append(textField) 


// **** Menu title **** //
let label = NSTextField (frame:NSMakeRect( _menuLeft, _wndH - 50, _menuWidth, 24 ))
 window.contentView!.addSubview (label)
 label.autoresizingMask = [.maxXMargin,.minYMargin]
 label.backgroundColor = .clear
 label.lineBreakMode = .byTruncatingTail
 label.isSelectable = false
 label.isBordered = true
 label.font = NSFont( name:"Menlo bold", size:14 )
 label.stringValue = menu.title

// **** Menu Disclosure Button **** //
let menuBtn = NSButton (frame:NSMakeRect( (_menuLeft + _menuWidth) - 20, _wndH - 50, 20, 24 ))
 menuBtn.bezelStyle = .disclosure
 menuBtn.autoresizingMask = [.maxXMargin,.minYMargin]
 menuBtn.title = ""
 menuBtn.action = #selector(self.menuBtnAction(_:))
 window.contentView!.addSubview (menuBtn)

// **** Quit btn **** //
let quitBtn = NSButton (frame:NSMakeRect( _wndW - 50, 10, 40, 40 ))
 quitBtn.bezelStyle = .circular
 quitBtn.autoresizingMask = [.minXMargin,.maxYMargin]
 quitBtn.title = "Q"
 quitBtn.action = #selector(NSApplication.terminate)
 window.contentView!.addSubview(quitBtn)

 
func applicationDidFinishLaunching(_ notification: Notification) 
 buildMenu()
 buildWnd()


func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool 
 return true



let appDelegate = AppDelegate()

// **** main.swift **** //
let app = NSApplication.shared
app.delegate = appDelegate
app.setActivationPolicy(.regular)
app.activate(ignoringOtherApps:true)
app.run()

【讨论】:

【参考方案2】:

第二种可能的替代方法是使用带有下拉菜单的 NSPopUpButton,它通过更改文本颜色来适应 DarkMode。和以前一样,每个 menuItem.view 中都嵌入了一个子类文本字段,以支持文本截断和对齐。可以按照前面给出的说明在 Xcode 中运行。

import Cocoa

var view = [NSTextField]()

class TextField: NSTextField 

override func mouseDown(with event: NSEvent) 
 print("selected = \(self.tag)")
 for i:Int in 0..<view.count 
  if(self.tag == i) 
   view[i].backgroundColor = .lightGray
    else 
   view[i].backgroundColor = .windowBackgroundColor
  
 




class AppDelegate: NSObject, NSApplicationDelegate 
var window:NSWindow!
var menu:NSMenu!
var pullDwn:NSPopUpButton!
var count:Int = 0

let _menuItemH : CGFloat = 20

func isDarkMode(view: NSView) -> Bool 
 if #available(OSX 10.14, *) 
  return view.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
 
 return false


@objc func myBtnAction(_ sender:Any ) 
 print(pullDwn.index(of:sender as! NSMenuItem))


func buildMenu() 
 let mainMenu = NSMenu()
 NSApp.mainMenu = mainMenu
 // **** App menu **** //
 let appMenuItem = NSMenuItem()
 mainMenu.addItem(appMenuItem)
 let appMenu = NSMenu()
 appMenuItem.submenu = appMenu
 appMenu.addItem(withTitle: "Quit", action:#selector(NSApplication.terminate), keyEquivalent: "q") 

    
func buildWnd() 
    
let _wndW : CGFloat = 400
let _wndH : CGFloat = 300

 window = NSWindow(contentRect:NSMakeRect(0,0,_wndW,_wndH),styleMask:[.titled, .closable, .miniaturizable, .resizable], backing:.buffered, defer:false)
 window.center()
 window.title = "Swift Test Window"
 window.makeKeyAndOrderFront(window)

// **** NSPopUpButton with Menu **** //
let menuItems = ["10%","25%","50%","75%","100%","200%","300%","400%","800%","longertext"]
pullDwn = NSPopUpButton(frame:NSMakeRect(80, _wndH - 50, 80, 30), pullsDown:true)
pullDwn.autoresizingMask = [.maxXMargin,.minYMargin]
let menu = pullDwn.menu
for mItem in menuItems
 let menuItem = NSMenuItem()
 menu?.addItem(menuItem)
 menuItem.title = "Fit"
 let textField = TextField(frame:NSMakeRect( 0, 0, pullDwn.frame.size.width, _menuItemH))
 menuItem.view = textField
 textField.alignment = .left // .left, .center, .right
 textField.stringValue = mItem
 textField.lineBreakMode = .byTruncatingTail
 if (isDarkMode(view: textField))
  textField.textColor = .white
  else 
  textField.textColor = .black
 
 textField.backgroundColor = .windowBackgroundColor
 textField.isEditable = false
 textField.tag = count
 textField.isBordered = false
 textField.font = NSFont( name:"Menlo", size:14 )
 count = count + 1
 view.append(textField) 

window.contentView!.addSubview (pullDwn)

// **** Quit btn **** //
let quitBtn = NSButton (frame:NSMakeRect( _wndW - 50, 10, 40, 40 ))
 quitBtn.bezelStyle = .circular
 quitBtn.autoresizingMask = [.minXMargin,.maxYMargin]
 quitBtn.title = "Q"
 quitBtn.action = #selector(NSApplication.terminate)
 window.contentView!.addSubview(quitBtn)

 
func applicationDidFinishLaunching(_ notification: Notification) 
 buildMenu()
 buildWnd()


func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool 
 return true



let appDelegate = AppDelegate()

// **** main.swift **** //
let app = NSApplication.shared
app.delegate = appDelegate
app.setActivationPolicy(.regular)
app.activate(ignoringOtherApps:true)
app.run()


【讨论】:

以上是关于具有自定义视图的 NSMenuItem 在滚动时消失的主要内容,如果未能解决你的问题,请参考以下文章

NSMenuItem 自定义视图未更新

NSMenuItem、自定义视图和 mouseUp 的奇怪问题:

如何删除自定义视图上方的 NSMenuItem 间隙

具有自定义视图的 ScrollView 不会滚动 - android?

集合视图,具有自定义布局,单元格在滚动时行为不端

自定义 UITableViewCell 的布局何时完成?