![](/img/trans.png)
[英]How to bind NSAttributeString (or NSMutableAttributedString)
[英]How to add padding to a NSMutableAttributedString?
我有一个标签,使用NSMutableAttributedString将文本写为:
我想做的是降低星号的顶部填充,以使它在MidY位置,甚至带有如下所示的Cuisine一词:
如何使用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
如果不是这样(并且您正在使用多个彼此叠放的标签),则可能只需要调整系列中每个标签的框架即可进行补偿。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.