【发布时间】:2016-04-23 12:52:22
【问题描述】:
我正在尝试弄清楚如何像屏幕截图中那样自定义 NSTextField。任何人都可以至少指出我的指南或正确的方向吗?我的意思是我知道您可以绘制背景和框,但是您如何告诉框它接受文本以及它应该是什么大小等?
非常感谢任何帮助。
【问题讨论】:
标签: objective-c macos cocoa custom-controls nstextfield
我正在尝试弄清楚如何像屏幕截图中那样自定义 NSTextField。任何人都可以至少指出我的指南或正确的方向吗?我的意思是我知道您可以绘制背景和框,但是您如何告诉框它接受文本以及它应该是什么大小等?
非常感谢任何帮助。
【问题讨论】:
标签: objective-c macos cocoa custom-controls nstextfield
由于实际文本似乎没有与边框重叠,因此一种方法是使用自定义视图类来绘制边框并在其中放置一个 NSTextView 来进行文本输入。只需将 NSTextView 设置为无边框并将背景颜色与视图匹配即可。
如果只是偶尔需要输入并且您想要一个轻量级控件,您甚至可以考虑为文本使用标签,或者简单地让 NSString 对象使用-drawInRext:withAttribures: 绘制自己并获取共享的 NSTextField 并将其放在顶部用于编辑。这就是 NSTableView 例如实现编辑的方式。
我已经为我拥有的一个选项卡式控件实现了类似的功能,它支持通过双击来编辑标题(如 excel 选项卡)。这里有一些代码如何获取共享文本编辑器作为灵感。然后您需要通过委托方法管理编辑过程。
-(BOOL)beginEditLabelInteractiveForTab:(NSInteger)index {
if (![self.window makeFirstResponder:self.window]) { // Try to make window first responder to ensure the shared field editor is available.
return NO;
};
NSTextView *tv = (NSTextView *)[self.window fieldEditor:YES forObject:nil]; // take the shared field editor and configure it
if (!tv) { // Did not get the field editor
return NO;
}
// Set font and location
[tv setVerticallyResizable:NO];
[tv setFont:self.textFont];
[tv setBackgroundColor:self.selectedFieldColor];
[tv setTextColor:self.editingColor];
[tv setEditable:YES];
editedTab = [self.tabs objectAtIndex:index];
tv.string = editedTab.label; // Set text
CGFloat w = editedTab.coreWidth + BSTeditorExtraPadding; // Slightly larger to fit the cursor
CGFloat h = (self.tabHeight < (self.preferredTextHeight-(2 * BSTstdYTextOffset))) ? (self.tabHeight-(2 * BSTstdYTextOffset)) : self.preferredTextHeight; // Text height or tab ht - 4 whichever is less
[tv setFrameSize:NSMakeSize(w,h)];
// x poistion is set in owner draw method to match location of tab
tv.textContainer.lineFragmentPadding = 0; // remove padding for alignment with text below
tv.delegate = self;
[self addSubview:tv];
[self.window makeFirstResponder:tv];
self.labelEditor = tv; // Store a reference also used as a flag
return YES;
}
【讨论】:
老实说,我只看到了两种方法:继承一个 NSTextField 并根据您的需要对其进行外观,但您将面临很多限制,或者创建您自己的类,看起来像一个 NSTextfield。
在第二个选项中,您绘制背景、边框、标签、图标、光标。此外,您可以为光标设置动画,根据文本字段的状态更改颜色和字体。这需要做很多工作,并且可能已经有一个很酷的库可以满足您的需求。
在这两种情况下,您都需要管理键盘以使用您想要的键盘(例如,用于填写电子邮件地址的电子邮件键盘)。
【讨论】: