我想创建一个文本如下的UILabel
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9wVHE3ay5wbmcifQ==” alt =“在此处输入图像说明”>
我该怎么做?当文本较小时,该行也应较小。
SWIFT 4 UPDATE CODE
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your Text")
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
然后:
yourLabel.attributedText = attributeString
要敲击字符串的一部分然后提供范围
let somePartStringRange = (yourStringHere as NSString).range(of: "Text")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: somePartStringRange)
Objective-C
在iOS 6.0>中 UILabel
支持NSAttributedString
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your String here"];
[attributeString addAttribute:NSStrikethroughStyleAttributeName
value:@2
range:NSMakeRange(0, [attributeString length])];
Swift
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your String here")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
定义:
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)aRange
Parameters List:
name:指定属性名称的字符串。属性键可以由另一个框架提供,也可以是您定义的自定义键。有关在哪里可以找到系统提供的属性键的信息,请参见《 NSAttributedString类参考》中的概述部分。
value:与名称关联的属性值。
aRange:指定属性/值对适用的字符范围。
然后
yourLabel.attributedText = attributeString;
对于lesser than iOS 6.0 versions
,您需要3-rd party component
才能执行此操作。其中一个是TTTAttributedLabel,另一个是OHAttributedLabel。
Swift 5
Swift 4.2
使用下面的代码
对于那些遇到多行文字提示问题的人>
let attributedString = NSMutableAttributedString(string: item.name!)
//necessary if UILabel text is multilines
attributedString.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.darkGray, range: NSMakeRange(0, attributedString.length))
cell.lblName.attributedText = attributedString
创建字符串扩展并在下面添加方法
这是您可以在Swift 4中使用的,因为NSStrikethroughStyleAttributeName已更改为NSAttributedStringKey.strikethroughStyle
将文本属性更改为属性并选择文本,然后单击鼠标右键以获取字体属性。单击删除线。
在Swift中,将枚举用于单个删除线样式:
let attrString = NSAttributedString(string: "Label Text", attributes: [NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
label.attributedText = attrString
其他删除线样式(记住使用.rawValue访问枚举]]]
删除线模式(与样式进行或):
指定删除线仅应应用于单词(而不是空格):
对于这种简单情况,我更喜欢NSAttributedString
而不是NSMutableAttributedString
:
SWIFT CODE
Swift 5.0中的删除线
SWIFT 4
您可以使用NSMutableAttributedString在IOS 6中完成。
在Swift iOS中删除UILabel文本。请尝试这个对我有用
对于任何希望在表视图单元格(Swift)中执行此操作的人,您必须像这样设置.attributeText: