[iOS/Swift] UILabel에 취소선 적용하기

Hoojeong Kim·2022년 3월 18일
0
post-thumbnail

요즘 패스트캠퍼스 강의 들으면서 공부하고 있는데, 강의를 보며 to-do list 앱을 만들다가 취소선을 추가하고 싶어졌다!!
참고로 내가 본 강의는 요기 이씀


문자열에 취소선을 긋기 위해 NSAttributedString을 사용한다.

NSAttributedString

NSAttributedString은 문자열과 문자열에 대한 Attribute들에 대한 정보를 갖고 있는 객체이다.
또한 딕셔너리 형태 관리되므로, key, value 쌍을 사용해 어떤 속성을 적용할지 결정할 수 있다.

취소선 외에도 색을 바꾸거나, 특정 문자열만 bold 처리하는 등, 다양한 작업을 할 수 있다.
NSAttributedString의 Mutable 버전도 있다. NSMutableAttributedString으로, NSAttributedString 기능에 더해서 글자를 바꾸거나 지우는 등 다양한 작업을 할 수 있다.

자세한 내용은 아래의 reference 참고하기!

구현하기

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

적용하기

@IBOutlet weak var textLabel: UILabel!

textLabel.attributedText = textLabel.text?.strikeThrough()

적용 예시

구현하고 있던 to-do list 앱에 적용해봤다!

profile
나 애기 개발자 👶🏻

0개의 댓글