[英]How to force the cursor to be an “arrowCursor” when it hovers a NSButton that is inside a NSTextView?
好的,問題來了:
我有一個NSTextView
並使用以下方法添加我的自定義NSButton
:
[_textView addSubview:button];
然后,在我的NSButton
子類中,我有(以及NSTrackingArea
東西):
- (void)mouseEntered:(NSEvent *)event{
[[NSCursor arrowCursor] set];
}
- (void)mouseExited:(NSEvent *)theEvent{
[[NSCursor arrowCursor] set];
}
- (void)mouseDown:(NSEvent *)theEvent{
[[NSCursor arrowCursor] set];
}
- (void)mouseUp:(NSEvent *)theEvent{
[[NSCursor arrowCursor] set];
}
但是當我懸停它時,光標仍然是同一個IBeamCursor
(因為它是一個NSTextView
)。 只有當我按下按鈕時,光標才會更新。 然后,當我移動鼠標時,仍然在按鈕內,光標回到IBeamCursor
。
關於如何做到這一點的任何想法? 謝謝!
添加僅跟蹤進入/退出事件的跟蹤區域對於NSTextView
子視圖似乎是不夠的。 不知何故, textview 總是獲勝並將其設置為IBeamCursor
。
在NSButton
子類中添加跟蹤區域時,您可以嘗試始終啟用對鼠標移動事件 ( NSTrackingMouseMoved
) 的跟蹤:
#import "SSWHoverButton.h"
@interface SSWHoverButton()
{
NSTrackingArea* trackingArea;
}
@end
@implementation SSWHoverButton
- (void)mouseMoved:(NSEvent*)theEvent
{
[[NSCursor arrowCursor] set];
}
- (void)updateTrackingAreas
{
if(trackingArea != nil)
{
[self removeTrackingArea:trackingArea];
}
NSTrackingAreaOptions opts = (NSTrackingMouseMoved|NSTrackingActiveAlways);
trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
options:opts
owner:self
userInfo:nil];
[self addTrackingArea:trackingArea];
}
- (void)dealloc
{
[self removeTrackingArea:trackingArea];
}
@end
Swift 5 變體:
import Cocoa
class InsideTextButton: NSButton {
var trackingArea: NSTrackingArea?
override func mouseMoved(with event: NSEvent) {
NSCursor.arrow.set()
}
override func updateTrackingAreas() {
if let area = trackingArea {
removeTrackingArea(area)
}
trackingArea = NSTrackingArea(rect: self.bounds, options: [.mouseMoved, .activeAlways], owner: self, userInfo: nil)
if let area = trackingArea {
addTrackingArea(area)
}
}
deinit {
if let area = trackingArea {
removeTrackingArea(area)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.