1. Tab 键不在多个NSTextField间自动切换
在使用addSubView或replaceSubView命令在NSWindow或NSView中动态替换视图
在动态改变window上的视图后,Tab 键不在多个NSTextField间自动切换。
解决:
先看window的相关属相和方法:
@property BOOL autorecalculatesKeyViewLoop;
- (void)recalculateKeyViewLoop;
- 创建window时,在代码或XIB中,将window的 autorecalculatesKeyViewLoop 设置成 true:
2. 重新计算window 的view loop
[window recalculateKeyViewLoop];
2. 编辑状态才绘制背景
我的需求是非编辑时就是一个无背景的label,编辑时,白色背景+黑色字体
方式: 重写 NSTextFieldCell的方法 ‘setUpFieldEditorAttributes’
class CTextFieldCell: NSTextFieldCell {
/**
If the receiver is disabled, this method sets the text color to dark gray; otherwise the method sets it to the default color. If the receiver has a bezeled border, this method sets the background to the default color for text backgrounds; otherwise, the method sets it to the color of the receiver’s NSControl object.
You should not use this method to substitute a new field editor. setUpFieldEditorAttributes: is intended to modify the attributes of the text object (that is, the field editor) passed into it and return that text object. If you want to substitute your own field editor, use the fieldEditor:forObject: method or the windowWillReturnFieldEditor:toObject: delegate method of NSWindow.
*/
override func setUpFieldEditorAttributes(_ textObj: NSText) -> NSText {
let result = super.setUpFieldEditorAttributes(textObj)
result.drawsBackground = true
result.textColor = .black
result.backgroundColor = .white
result.appearance = NSAppearance.init(named: .aqua)
//result.textColor = .black
return result
}
}
stackoverflow的参考信息:
I just did this recently, in a tableView. You need to use a custom cell and fieldEditor. Specifically, you need to call setDrawsbackground:YES
on the NSText/NSTextView object that is the field editor, and setBackground: to configure your color of choice. There are two places to set up a custom field editor.
One is to implement setUpFieldEditorAttributes:
on a custom NSTextFieldCell
subclass that you have configured your NSTextField to use, and another is to use the window
or window delegate
method windowWillReturnFieldEditor:toObject:
.
Note that if the first method doesn’t work for a particular setting, sometimes you need to use the second, because it gets in earlier in the codepath.