我有一个标签使用NSMutableAttributedString写出文本:
我想要做的是降低星号的顶部填充,以便它的midY甚至是下面的“烹饪”这个词:
如何使用NSMutableAttributedString添加填充?
我知道我可以单独使用星号创建一个单独的标签,并使用带常量的锚点来居中它但我希望看到如何使用NSMutableAttributedString
let cuisineLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
let attributedText = NSMutableAttributedString(string: "Cuisine ", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17), NSAttributedStringKey.foregroundColor: UIColor.lightGray])
attributedText.append(NSAttributedString(string: "*", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24), NSAttributedStringKey.foregroundColor: UIColor.red]))
label.attributedText = attributedText
return label
}()
baselineOffset
属性键用于此目的。
let cuisine = NSMutableAttributedString(string: "Cuisine")
let asterisk = NSAttributedString(string: "*", attributes: [.baselineOffset: -3])
cuisine.append(asterisk)
显然,您必须使用文本其余部分的字体大小来计算偏移量。这就是为什么我认为使用全宽星号(*)更容易。
带有全宽星号的结果(您可能希望其字体大小为字符串其余部分的字体大小的比例):
正如Code Different指出的那样,您可以使用baselineOffset
属性执行此操作。 -8
的值应该适用于您的情况:
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
let cuisineLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
let attributedText = NSMutableAttributedString(string: "Cuisine ", attributes: [
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17),
NSAttributedStringKey.foregroundColor: UIColor.lightGray])
attributedText.append(NSAttributedString(string: "*", attributes: [
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24),
NSAttributedStringKey.baselineOffset: -8,
NSAttributedStringKey.foregroundColor: UIColor.red]))
label.attributedText = attributedText
return label
}()
view.addSubview(cuisineLabel)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
如果由于新基线并且您使用的是多线标签而导致线高度偏移混乱,请尝试使用lineHeightMultiple
:
let lineStyle = NSParagraphStyle()
lineStyle.lineHeightMultiple = 0.8
...
NSAttributedStringKey.paragraphStyle = style
如果不是(并且您使用多个标签堆叠在一起),那么您可能只需要调整系列中每个标签的框架以进行补偿。