UILabel with text struck through

2020-01-25 13:22发布

I want to create a UILabel in which the text is like this

enter image description here

How can I do this? When the text is small, the line should also be small.

16条回答
Melony?
2楼-- · 2020-01-25 13:23

Use below code

NSString* strPrice = @"£399.95";

NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:strPrice];

[finalString addAttribute: NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range: NSMakeRange(0, [titleString length])];
self.lblOldPrice.attributedText = finalString;   
查看更多
We Are One
3楼-- · 2020-01-25 13:25

SWIFT CODE

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

then:

yourLabel.attributedText = attributeString

Thanks to Prince answer ;)

查看更多
聊天终结者
4楼-- · 2020-01-25 13:26

Change the text property to attributed and select the text and right click to get the font property. Click on the strikethrough. Screenshot

查看更多
ゆ 、 Hurt°
5楼-- · 2020-01-25 13:29

Create String extension and add below method

static func makeSlashText(_ text:String) -> NSAttributedString {


 let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: text)
        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

return attributeString 

}

then use for your label like this

yourLabel.attributedText = String.makeSlashText("Hello World!")
查看更多
神经病院院长
6楼-- · 2020-01-25 13:32

For anyone looking on how to do this in a tableview cell (Swift) you have to set the .attributeText like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TheCell")!

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: message)
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

    cell.textLabel?.attributedText =  attributeString

    return cell
    }

If you want to remove the strikethrough do this otherwise it will stick around!:

cell.textLabel?.attributedText =  nil
查看更多
三岁会撩人
7楼-- · 2020-01-25 13:34

Swift 5

extension String {

  /// Apply strike font on text
  func strikeThrough() -> NSAttributedString {
    let attributeString = NSMutableAttributedString(string: self)
    attributeString.addAttribute(
      NSAttributedString.Key.strikethroughStyle,
      value: 1,
      range: NSRange(location: 0, length: attributeString.length))

      return attributeString
     }
   }

Example:

someLabel.attributedText = someText.strikeThrough()
查看更多
登录 后发表回答