如何在绘制矩形中为 NSTextField 或 NSTextVew 实现自定义对焦环
我想为我的 NSTextView 子类绘制一个自定义焦点环(默认情况下没有焦点环)。我设法通过覆盖父 NSScrollView
drawRect
并添加以下代码来实现它:
- (void)drawRect:(NSRect)dirtyRect {
if (focused) {
NSSetFocusRingStyle(NSFocusRingOnly);
NSRectFill(dirtyRect);
}
[super drawRect:dirtyRect];
}
但是,我想绘制自己的自定义聚焦环。我找了又找这方面的例子,也尝试自己乱写,但没有成功。我遇到的最大问题是,无论我怎么做,它都会被裁剪到 NSScrollView
/NSTextView
框架。
谢谢。
I want to draw a custom focus ring for my NSTextView
subclass (which doesn't have a focus ring by default). I managed to implement it by overriding the parent NSScrollView
drawRect
and adding this code:
- (void)drawRect:(NSRect)dirtyRect {
if (focused) {
NSSetFocusRingStyle(NSFocusRingOnly);
NSRectFill(dirtyRect);
}
[super drawRect:dirtyRect];
}
However, I want to draw my own, custom focus ring. I have searched and searched for examples of this, and tried messing around and writing it myself, to no avail. The biggest issue I have is the fact that it will get cropped to the NSScrollView
/NSTextView
frame, no matter how I do it.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为 10.7+ 更新此答案:
现在您应该覆盖
drawFocusRingMask
进行渲染(只需绘制形状;系统将处理颜色/样式),并覆盖focusRingMaskBounds
进行提示在它的边界。另外,如果您以某种系统无法自行识别的方式更改形状,请调用noteFocusRingMaskChanged
。(下面是之前的答案,需要较旧的 API:)
在 Carbon 框架中,有
HIThemeBeginFocus()
和HIThemeEndFocus()< /code>,它允许您使任何一系列绘图(例如矩形或形状)具有自动“聚焦”外观。需要 Mac OS X 10.5 或更高版本。
这直接使用Core Graphics。要从 Cocoa 中的
drawRect:
方法查找 CG 上下文,您需要执行以下操作:为了避免剪切,一种选择是使用父视图(例如
NSBox< /code> 没有边框)以提供额外的填充。在父视图中不会被剪切的插入位置执行自定义绘图;换句话说,给人一种视图比实际矩形小一点的错觉。
Updating this answer for 10.7+:
Now you should override
drawFocusRingMask
to render (simply drawing a shape; the system will take care of color/style), and overridefocusRingMaskBounds
to hint at its boundaries. Also, callnoteFocusRingMaskChanged
if you change the shape in some way that the system could not figure out on its own.(Below is the previous answer, requiring older APIs:)
In the Carbon framework there are
HIThemeBeginFocus()
andHIThemeEndFocus()
, which allow you to cause any series of drawings (such as a rectangle or shape) to have an automatic "focused" appearance. Requires Mac OS X 10.5 or later.This uses Core Graphics directly. To find the CG context from a
drawRect:
method in Cocoa, you'd do something like:As far as avoiding clipping, one option is to use a parent view (such as an
NSBox
that has no border) to give extra padding. Perform the custom drawing at an inset location in the parent view that won't be clipped; in other words, give the illusion that the view is a bit smaller than its actual rectangle.