在NSTextField中设置文本垂直中心,可以通过以下方法实现:
let textField = NSTextField()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.baseWritingDirection = .natural
paragraphStyle.lineSpacing = 2.0
paragraphStyle.paragraphSpacing = 2.0
paragraphStyle.firstLineHeadIndent = 0.0
paragraphStyle.headIndent = 0.0
paragraphStyle.tailIndent = 0.0
paragraphStyle.minimumLineHeight = 16.0
paragraphStyle.maximumLineHeight = 16.0
let attributedString = NSAttributedString(string: "Hello World", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
textField.attributedStringValue = attributedString
let textField = NSTextField()
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: textField.bounds.size)
textContainer.widthTracksTextView = true
textContainer.heightTracksTextView = true
textContainer.maximumNumberOfLines = 1
textContainer.lineBreakMode = .byWordWrapping
textContainer.lineFragmentPadding = 0.0
layoutManager.addTextContainer(textContainer)
textField.textContainer = textContainer
textField.layoutManager = layoutManager
textField.textContainerInset = NSSize(width: 0, height: 0)
textField.isEditable = false
textField.isSelectable = false
textField.isBezeled = false
textField.drawsBackground = false
textField.stringValue = "Hello World"
以上两种方法都可以实现在NSTextField中设置文本垂直中心。
领取专属 10元无门槛券
手把手带您无忧上云