将上标放在xcode8中的标签中

时间:2017-09-04 06:42:23

标签: swift xcode8

我正在创建一个数学应用程序,并希望有一个上标2.我一直无法找到xcode 8的解决方案,这不是基线的设置

finalFunc.text = "Converted: \(printA)(x+\(printB))^2+\(printC)" 

3 个答案:

答案 0 :(得分:0)

使用此代码 -

let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "xcode8", attributes: [NSFontAttributeName:font!])
attString.setAttributes([NSFontAttributeName:fontSuper!,NSBaselineOffsetAttributeName:10], range: NSRange(location:5,length:1))
label1.attributedText = attString;

输出 -

enter image description here

答案 1 :(得分:0)

对于简单易用的Swift解决方案,您可能需要结帐 HandyUIKit 。将其导入项目后(例如通过Carthage - 参见README中的说明),您可以执行以下操作:

import HandyUIKit

let someFont = UIFont.systemFont(ofSize: 20, weight: .medium)
"Converted: \(printA)(x+\(printB))^{2}+\(printC)".superscripted(font: someFont)

最后一行将返回NSAttributedString,其外观与您正在寻找的内容完全相同。只需将其分配给UILabel attributedText 属性,然后即可!

如果您正在寻找下标文字,请改用subscripted(font:)。它将识别CO_{2}之类的结构。如果你想组合两者,还有superAndSubscripted(font:)

有关更多信息和其他示例,请参阅docs

答案 2 :(得分:0)

已针对Swift4

更新
let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "xcode8", attributes: [NSAttributedString.Key.font:font!])
attString.setAttributes([NSAttributedString.Key.font:fontSuper!,NSAttributedString.Key.baselineOffset:10], range: NSRange(location:5,length:1))

labelname.attributedText = attString