[英]NSButton Subclass not sending event
我正在繼承 NSButton 並且在我認為非常簡單的事情上遇到了很多麻煩。 我在視覺上接近我需要的位置,但按鈕在按下時似乎不再發送事件。 這個按鈕被放置在 IB 中並連接到包含視圖的控制器類中的一個動作。
這是自定義 NSButton 和 NSButtonCell 類的代碼。 您將在 MouseUp 函數中看到一些我一直在嘗試使其工作的方法。 動作和目標似乎都為空,即使該信息應該來自 IB,我認為......
震驚的是,這個問題沒有被問過並回答了 100 次,但如果有,我找不到它。
另外,作為一個附帶問題,我注意到 ButtonCell 概念似乎已被棄用。 關於如何在不使用紐扣電池的情況下執行此操作的建議也將不勝感激!
import Cocoa
class TestButton: NSButton {
static let buttonFont = NSFont(name: "Avenir-Black ", size: 14)!
static let textColor = NSColor(red:0.84, green:1.00, blue:0.60, alpha:1.00)
static let buttonColorActive = NSColor(red:0.43, green:0.72, blue:0.00, alpha:1.00)
static let buttonColorDisabled = NSColor(red:0.72, green:0.86, blue:0.50, alpha:1.00)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame frameRect: NSRect) {
super.init(frame:frameRect)
}
override class func cellClass() -> AnyClass? {
return TestButtonCell.self
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
}
override func awakeFromNib() {
// Replace Cell
let oldCell = self.cell
let cell = TestButtonCell(textCell: oldCell?.title ?? "TestButton" )
self.cell = cell
// Add Tracking
let tracking = NSTrackingArea(rect: self.bounds, options: [NSTrackingAreaOptions.ActiveAlways ,NSTrackingAreaOptions.MouseEnteredAndExited] , owner: self, userInfo: nil)
self.addTrackingArea(tracking)
//Set Background Color
setBGColor(TestButton.buttonColorActive)
self.sendActionOn(NSEventMask.LeftMouseUp)
}
func setBGColor(color:NSColor){
if let cell = cell as? TestButtonCell {
cell.setBGColor(color)
}
}
//Mouse Functions
override func mouseEntered(event: NSEvent) {
setBGColor(TestButton.buttonColorDisabled)
}
override func mouseExited(event: NSEvent) {
setBGColor(TestButton.buttonColorActive)
}
override func mouseDown(theEvent: NSEvent) {
self.highlighted = true
super.mouseDown(theEvent)
self.mouseUp(theEvent)
}
override func mouseUp(theEvent: NSEvent) {
super.mouseUp(theEvent)
// Swift.print(self.action, self.target)
// Swift.print(self.cell?.action, self.cell?.target)
// sendAction(self.action, to:self)
// self.performClick(self)
}
}
class TestButtonCell:NSButtonCell {
func setBGColor(color:NSColor){
self.backgroundColor = color
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(textCell string: String) {
super.init(textCell: string)
self.bordered = false
let style = NSMutableParagraphStyle()
style.alignment = .Center
let attributes = [
NSForegroundColorAttributeName: TestButton.textColor,
NSFontAttributeName: TestButton.buttonFont,
NSParagraphStyleAttributeName: style
] as [String : AnyObject]
let attributedTitle = NSAttributedString(string: title, attributes: attributes)
self.attributedTitle = attributedTitle
}
}
想通了這一點。 我沒有調用 super.awakeFromNib(),而且我還需要在使用之前保留原始 NSButtonCell 的動作和目標。 不過我要放棄牢房——似乎完全不需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.