developer tip

텍스트가있는 UILabel

optionbox 2020. 8. 6. 08:17
반응형

텍스트가있는 UILabel


UILabel텍스트가 이런 식 으로 만들고 싶습니다

여기에 이미지 설명을 입력하십시오

어떻게해야합니까? 텍스트가 작 으면 줄도 작아야합니다.


스위프트 코드

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, 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)

목표 -C

에서 아이폰 OS 6.0> UILabel 지원NSAttributedString

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your String here"];
[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:@2
                        range:NSMakeRange(0, [attributeString length])];

빠른

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 : name과 관련된 속성 값입니다.

aRange : 지정된 속성 / 값 쌍이 적용되는 문자 범위.

그때

yourLabel.attributedText = attributeString;

들어 lesser than iOS 6.0 versions당신이 필요로 3-rd party component이 작업을 수행 할 수 있습니다. 그중 하나는 TTTAttributedLabel 이고 다른 하나는 OHAttributedLabel 입니다.


이 간단한 경우 NSAttributedString보다는 선호합니다 NSMutableAttributedString.

NSAttributedString * title =
    [[NSAttributedString alloc] initWithString:@"$198"
                                    attributes:@{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle)}];
[label setAttributedText:title];

속성이 지정된 문자열 NSUnderlineStyleAttributeNameNSStrikethroughStyleAttributeName속성을 모두 지정하기위한 상수 :

typedef enum : NSInteger {  
  NSUnderlineStyleNone = 0x00,  
  NSUnderlineStyleSingle = 0x01,  
  NSUnderlineStyleThick = 0x02,  
  NSUnderlineStyleDouble = 0x09,  
  NSUnderlinePatternSolid = 0x0000,  
  NSUnderlinePatternDot = 0x0100,  
  NSUnderlinePatternDash = 0x0200,  
  NSUnderlinePatternDashDot = 0x0300,  
  NSUnderlinePatternDashDotDot = 0x0400,  
  NSUnderlineByWord = 0x8000  
} NSUnderlineStyle;  

Swift에서 단일 취소 선 스타일에 열거 형을 사용하십시오.

let attrString = NSAttributedString(string: "Label Text", attributes: [NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
label.attributedText = attrString

추가 취소 선 스타일 ( .rawValue를 사용하여 열거 형에 액세스해야 함 ) :

  • NSUnderlineStyle.StyleNone
  • NSUnderlineStyle.StyleSingle
  • NSUnderlineStyle.StyleThick
  • NSUnderlineStyle.StyleDouble

취소 선 패턴 (스타일과 OR)

  • NSUnderlineStyle.PatternDot
  • NSUnderlineStyle.PatternDash
  • NSUnderlineStyle.PatternDashDot
  • NSUnderlineStyle.PatternDashDotDot

Specify that the strikethrough should only be applied across words (not spaces):

  • NSUnderlineStyle.ByWord

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 ;)


Strikethrough in Swift 4.0

let attributeString =  NSMutableAttributedString(string: "Your Text")

attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle,
                                 value: NSUnderlineStyle.styleSingle.rawValue,
                                 range: NSMakeRange(0, attributeString.length))
self.yourLabel.attributedText = attributeString

It worked for me like a charm.

Use it as extension

extension String {
    func strikeThrough() -> NSAttributedString {
        let attributeString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0,attributeString.length))
        return attributeString
    }
}

Call like this

myLabel.attributedText = "my string".strikeThrough()

SWIFT 4

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text Goes Here")
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
    self.lbl_productPrice.attributedText = attributeString

Other method is to used String Extension
Extension

extension String{
    func strikeThrough()->NSAttributedString{
        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
        return attributeString
    }
}

Calling the function : Used it like so

testUILabel.attributedText = "Your Text Goes Here!".strikeThrough()

Credit to @Yahya - update Dec 2017
Credit to @kuzdu - update Aug 2018


You can do it in IOS 6 using NSMutableAttributedString.

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc]initWithString:@"$198"];
[attString addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:NSMakeRange(0,[attString length])];
yourLabel.attributedText = attString;

Strike out UILabel text in Swift iOS. PLease try this it's working for me

let attributedString = NSMutableAttributedString(string:"12345")
                      attributedString.addAttribute(NSAttributedStringKey.baselineOffset, value: 0, range: NSMakeRange(0, attributedString.length))
                      attributedString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSNumber(value: NSUnderlineStyle.styleThick.rawValue), range: NSMakeRange(0, attributedString.length))
                      attributedString.addAttribute(NSAttributedStringKey.strikethroughColor, value: UIColor.gray, range: NSMakeRange(0, attributedString.length))

 yourLabel.attributedText = attributedString

You can change your "strikethroughStyle" like styleSingle, styleThick,styleDouble 여기에 이미지 설명을 입력하십시오


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
    }

취소 선을 제거하려면이 작업을 수행하십시오. 그렇지 않으면 붙어 있습니다! :

cell.textLabel?.attributedText =  nil

스위프트 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
     }
   }

예:

someLabel.attributedText = someText.strikeThrough()

스위프트 4.2

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: product.price)

attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attributeString.length))

lblPrice.attributedText = attributeString

아래 코드 사용

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;   

여러 줄로 된 텍스트 경고 문제가있는 사람들

    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

문자열 확장을 만들고 아래 메소드를 추가하십시오.

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


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

return attributeString 

}

다음과 같이 라벨에 사용하십시오.

yourLabel.attributedText = String.makeSlashText("Hello World!")

NSStrikethroughStyleAttributeName이 NSAttributedStringKey로 변경되었으므로 Swift 4에서 사용할 수있는 것입니다.

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")

attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))

self.lbl.attributedText = attributeString

텍스트 속성을 속성으로 변경하고 텍스트를 선택하고 마우스 오른쪽 버튼을 클릭하여 글꼴 속성을 가져옵니다. 취소 선을 클릭하십시오.스크린 샷

참고 URL : https://stackoverflow.com/questions/13133014/uilabel-with-text-struck-through

반응형