我遇到一个小问题,就是我的标签文本已展开,如下图所示:
我想知道如何获取普通文本。
如果您知道该怎么做,请告诉我。
这是代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.updateUserActivityOnApp(isFirstConnection: false)
//print(self.view.frame.size.height - (self.extraPhoto1.frame.size.height + self.extraPhoto1.frame.origin.y))
if self.view.frame.size.height - (self.extraPhoto1.frame.size.height + self.extraPhoto1.frame.origin.y) >= 140 {
descriptionTopSpaceConstraint.constant = 20
self.view.layoutIfNeeded()
}
profilePicture.image = nil
descriptionTxtView.isEditable = false
descriptionTxtView.text! = ""
extraPhoto1.image = nil
extraPhoto2.image = nil
extraPhoto3.image = nil
usernameCountryLbl.text! = "Loading..."
self.navigationItem.setHidesBackButton(true, animated:true)
var attrStr = NSMutableAttributedString(string: "this is some very long test string for justification. this is some very long test string for justification. this is some very long test string for justification. this is some very long test string for justification")
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.justified
paragraphStyle.hyphenationFactor = 1
attrStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attrStr.length))
attrStr.addAttribute(NSAttributedString.Key.kern, value: -0.1, range: NSMakeRange(0, attrStr.length))
self.descriptionTxtView.attributedText = attrStr // label is the UILabel where you want the text to be displayed
self.descriptionTxtView.sizeToFit()
}
非常感谢您
答案 0 :(得分:1)
将文本视图的textAlignment
设置为.natural
,而不是.justified
。
答案 1 :(得分:1)
textAligment.natural
(如@Rob所述)是您不关心文本是否合理的一种选择。否则,唯一的方法是使用NSMutableAttributedString
和hyphenationFactor
。如果您需要证明其合理性,可以执行以下操作:
var attrStr = NSMutableAttributedString(string: "this is some very long test string for justification. this is some very long test string for justification. this is some very long test string for justification. this is some very long test string for justification")
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.justified
paragraphStyle.hyphenationFactor = 1
attrStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attrStr.length))
attrStr.addAttribute(NSAttributedString.Key.kern, value: -0.1, range: NSMakeRange(0, attrStr.length))
label.attributedText = attrStr // label is the UILabel where you want the text to be displayed
label.sizeToFit()
label.numberOfLines = 0