macOS - NSTextField

1. Tab 键不在多个NSTextField间自动切换

在使用addSubView或replaceSubView命令在NSWindow或NSView中动态替换视图

在动态改变window上的视图后,Tab 键不在多个NSTextField间自动切换。
解决:
先看window的相关属相和方法:

@property BOOL autorecalculatesKeyViewLoop;
- (void)recalculateKeyViewLoop;
  1. 创建window时,在代码或XIB中,将window的 autorecalculatesKeyViewLoop 设置成 true:

    2. 重新计算window 的view loop
 [window recalculateKeyViewLoop];

2. 编辑状态才绘制背景

我的需求是非编辑时就是一个无背景的label,编辑时,白色背景+黑色字体

stackoverflow

方式: 重写 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值