ixa*_*any 3 xcode padding nstextfield swift swift3
我想知道是否有可能设置边距或填充NSTextField?
我实现了或多或少的自定义文本字段(此屏幕截图中的第一个)...
...使用此代码:
myTextField.wantsLayer = true
myTextField.layer?.cornerRadius = 2.0
myTextField.layer?.borderWidth = 1.0
myTextField.layer?.borderColor = CGColor(red: 0.69, green: 0.69, blue: 0.69, alpha: 1.0)
Run Code Online (Sandbox Code Playgroud)
但是,感觉我必须在左侧添加一些填充,以便数字不会太靠近边框。这甚至可能吗?
没有简单明了的方法可以做到这一点,但就像 AppKit 中的许多事情一样,一旦你确切地弄清楚你需要子类化什么,这并不太难。我遇到了 Hem Dutt 的这个例子,在我对 macOS 10.12 的测试中,这种方法似乎很有效。简而言之,您只需要子类化NSTextFieldCell和覆盖一些方法来更改文本框架。这是 Swift 3 中的一个变体:
class CustomTextFieldCell: NSTextFieldCell {
private static let padding = CGSize(width: 4.0, height: 2.0)
override func cellSize(forBounds rect: NSRect) -> NSSize {
var size = super.cellSize(forBounds: rect)
size.height += (CustomTextFieldCell.padding.height * 2)
return size
}
override func titleRect(forBounds rect: NSRect) -> NSRect {
return rect.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
}
override func edit(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, event: NSEvent?) {
let insetRect = rect.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
super.edit(withFrame: insetRect, in: controlView, editor: textObj, delegate: delegate, event: event)
}
override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
let insetRect = rect.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
super.select(withFrame: insetRect, in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
let insetRect = cellFrame.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
super.drawInterior(withFrame: insetRect, in: controlView)
}
}
Run Code Online (Sandbox Code Playgroud)
我对原来的做了一个显着的改变——覆盖cellSize(forBounds:)以增加单元格的最小高度。我正在使用自动布局来自动调整单元格的大小,因此如果没有覆盖,我的文本就会被剪裁。
| 归档时间: |
|
| 查看次数: |
2970 次 |
| 最近记录: |