1
是否有可能在可编辑的NSTextField中绘制自定义对焦环?我搜索了整个网络,但找不到工作解决方案。我将NSTextField分类并覆盖“drawFocusRingMask”,但没有任何结果。NSTextField自定义对焦环
我的目标是要实现像一个在Mac OS Adressbook对焦环(在编辑一个人)
是否有可能在可编辑的NSTextField中绘制自定义对焦环?我搜索了整个网络,但找不到工作解决方案。我将NSTextField分类并覆盖“drawFocusRingMask”,但没有任何结果。NSTextField自定义对焦环
我的目标是要实现像一个在Mac OS Adressbook对焦环(在编辑一个人)
此代码的NSTextField的子类作品:
- (void)awakeFromNib {
self.focusRingType = NSFocusRingTypeNone;
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
BOOL focus = NO;
//check, if the NSTextField is focused
id firstResponder = self.window.firstResponder;
if ([firstResponder isKindOfClass:[NSTextView class]]) {
NSTextView *textView = (NSTextView*)firstResponder;
NSClipView *clipView = (NSClipView*)textView.superview;
NSTextField *textField = (NSTextField*)clipView.superview;
if (textField == self)
focus = YES;
}
if (focus) {
NSRect bounds = self.bounds;
NSRect outerRect = NSMakeRect(bounds.origin.x - 2,
bounds.origin.y - 2,
bounds.size.width + 4,
bounds.size.height + 4);
NSRect innerRect = NSInsetRect(outerRect, 1, 1);
NSBezierPath *clipPath = [NSBezierPath bezierPathWithRect:outerRect];
[clipPath appendBezierPath:[NSBezierPath bezierPathWithRect:innerRect]];
[clipPath setWindingRule:NSEvenOddWindingRule];
[clipPath setClip];
[[NSColor colorWithCalibratedWhite:0.6 alpha:1.0] setFill];
[[NSBezierPath bezierPathWithRect:outerRect] fill];
}
}
上面的回答是工作好! 以下是雨燕3.0的版本,我转换
class MyTextField: NSTextField {
override func awakeFromNib() {
self.focusRingType = NSFocusRingType.none
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
var focus = false
if let firstResponder = self.window?.firstResponder {
if firstResponder.isKind(of: NSTextView.self) {
let textView = firstResponder as! NSTextView
if let clipView = textView.superview {
if let textField = clipView.superview {
if textField == self {
focus = true
}
}
}
}
}
if focus {
let bounds = self.bounds
let outerRect = NSMakeRect(bounds.origin.x - 2, bounds.origin.y - 2, bounds.size.width + 4, bounds.size.height + 4)
let innerRect = NSInsetRect(outerRect, 1, 1)
let clipPath = NSBezierPath(rect: outerRect)
clipPath.append(NSBezierPath(rect: innerRect))
clipPath.windingRule = NSWindingRule.evenOddWindingRule
clipPath.setClip()
NSColor(calibratedWhite: 0.6, alpha: 1.0).setFill()
NSBezierPath(rect: outerRect).fill()
self.backgroundColor = NSColor(cgColor: CGColor(red: 1, green: 0.4, blue: 0.5, alpha: 0.4))
}
}
}
以及如何使用是如下
textView.select(withFrame: textView.frame, editor: NSText(), delegate: self, start, 0, length: 3)
您是否尝试过使用一个自定义字段编辑器? – Merlevede