用的是比较笨的办法,通过设置文字间距来实现,直接来代码
/// 创建订单选项视图
/// - Parameters:
/// - itemName: 选项名称,如:手机号 下单时间
/// - contentStr: 选项对应的具体值
/// - count: 选项名称的文字个数,如 手机号有3个文字,下单时间有4个文字
/// - Returns: 创建好的视图
func createOrderItemInfoView(itemName: String, contentStr: String, count: Int) -> UIView {
let contentView = UIView()
contentView.backgroundColor = .white
// 选项名称
let itemLabel = UILabel(text: itemName, textColor: normalNineColor, font: UIFont.pingFangSCRegular(size: 14))
itemLabel.tag = 1001
contentView.addSubview(itemLabel)
itemLabel.snp_makeConstraints { (make) in
make.left.equalToSuperview().offset(15)
make.centerY.equalToSuperview()
}
// 单个文字的宽度,设置为和字号差不多就行
let unit_w: CGFloat = 15
// 计算字间距
// 60 = unit_w * 4 最大长度度,即要显示的选项标题最大字数 例如:手机号=3 下单时间=4
let word_space = (60 - (CGFloat(count) * unit_w)) / CGFloat(count - 1)
// 设置间距
let attributeStr = NSMutableAttributedString(string: itemName)
attributeStr.addAttribute(.kern, value: word_space, range: NSRange(location: 0, length: itemName.count))
itemLabel.attributedText = attributeStr
// 冒号
let colonLabel = UILabel(text: ":", textColor: normalNineColor, font: UIFont.pingFangSCRegular(size: 14))
contentView.addSubview(colonLabel)
colonLabel.snp_makeConstraints { (make) in
// 注意要减去间距
make.left.equalTo(itemLabel.snp_right).offset(-word_space)
make.centerY.equalTo(itemLabel)
}
// 选项对应的值
let contentLabel = UILabel(text: contentStr, textColor: normalThreeColor, font: UIFont.pingFangSCRegular(size: 14))
contentLabel.tag = 1002
contentView.addSubview(contentLabel)
contentLabel.snp_makeConstraints { (make) in
make.left.equalToSuperview().offset(99)
make.centerY.equalToSuperview()
}
return contentView
}
调用
createOrderItemInfoView(itemName: "支付方式", contentStr: "微信支付", count: 4)