是否有可能在可编辑的NSTextField中绘制自定义对焦环?我搜索了整个网络,但无法找到可行的解决方案。我将NSTextField子类化并覆盖" drawFocusRingMask",但没有任何结果。
我的目标是实现像Mac OS Adressbook中那样的聚焦环(编辑人物时)
答案 0 :(得分:4)
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];
}
}
答案 1 :(得分:2)
以上答案运作良好! 下面是我转换的Swift 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)