所以我遇到了同样的问题,在this question and answer 的帮助下,我找到了一个不错的解决方案。
我想将标签节点的文本与自定义按钮节点(包裹在形状节点中以绘制轮廓的标签节点)对齐。
我还想将切换(开/关)按钮与标签节点的基线对齐,并使用与标签中文本的 xHeight 相同的高度。
红线表示所有标签和按钮都正确对齐。
所以为了做到这一点,我做了以下事情。
我创建了一个 Font 类,可用于从SKLabelNode 中的fontName 和fontSize 创建字体对象。
在内部,它将创建 NSFont (macOS) 或 UIFont (iOS)。并设置上升器、下降器属性。为方便起见,还有一个 getter 可以返回字体的最大可能高度。
import Foundation
#if os(macOS)
import Cocoa
#endif
#if os(iOS)
import UIKit
#endif
enum FontError: LocalizedError {
case invalidFont(String, CGFloat)
var errorDescription: String? {
switch self {
case .invalidFont(let name, let size):
return "Could not create font with name \(name) and size: \(size)"
}
}
}
class Font {
private(set) var name: String
private(set) var size: CGFloat
private(set) var ascender: CGFloat
private(set) var descender: CGFloat
private(set) var xHeight: CGFloat
var maxHeight: CGFloat {
return self.ascender + fabs(self.descender)
}
init(name: String, size: CGFloat) throws {
// check if font can be created, otherwise crash
// set ascender, descender, etc...
#if os(macOS)
guard let font = NSFont(name: name, size: size) else {
throw FontError.invalidFont(name, size)
}
self.ascender = font.ascender
self.descender = font.descender
self.xHeight = font.xHeight
#endif
#if os(iOS)
guard let font = UIFont(name: name, size: size) else {
throw FontError.invalidFont(name, size)
}
self.ascender = font.ascender
self.descender = font.descender
self.xHeight = font.xHeight
#endif
self.name = name
self.size = size
}
}
然后我在标签位置计算中使用 maxHeight。因此,例如在我的自定义 ButtonNode(包含 SKLabelNode 的 SKShapeNode)中,我执行以下操作(简化):
// in the constructor of my custom
// button node ...
let height = 30
self.label = SKLabelNode(text: "Back")
// in order to position properly, set
// vertical alignment to baseline
self.label.verticalAlignmentMode = .baseline
let font = try Font(name: self.label.fontName!, size: self.label.fontSize)
// depending on the font you might want to add
// an additional y offset to place labels
// higher or lower within the node
let yOffset = (height - font.maxHeight) / 2)
let labelWidth = self.label.calculateAccumulatedFrame().width
let labelFrame = CGRect(
x: 0,
y: 0,
width: labelWidth,
height: height
)
self.path = CGPath(roundedRect: labelFrame, cornerWidth: 5, cornerHeight: 5, transform: nil)
self.label.position = CGPoint(x: labelFrame.width / 2, y: yOffset)
PS:如果您不想创建单独的 Font 类,但仍希望代码在 iOS 和 macOS 上正常工作,您可以为 @987654335 创建一个类型别名@ 和 UIFont。由于您可以使用相同的构造函数,您只需要添加一个扩展来计算字体的最大高度 (ascender + abs(descender))。
我更喜欢创建一个类,以便在无法正确创建字体时抛出错误。