[231221] Today I Learned

YoungHyun Kim·2023년 12월 21일
1

TIL ✍️

목록 보기
23/68

1. extension 사용의 예시 (기능의 수평확장)


let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: self)
        attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle,
        value: NSUnderlineStyle.single.rawValue,
        range: NSMakeRange(0, attributeString.length))

위의 코드는 UILabelattributedText 프로퍼티에 취소선을 구현해주는 구문의 한 부분이다. 난 여태껏 이 구문을 취소선 구현해야하는 부분마다 적어서 사용했는데, 보다 코드를 짧게 만들 수 있는 방법인 extension을 사용하는 방법을... 이제야 알았다.

프로젝트 내에 내가 따로 구현한 extension은 아래처럼 구성했다.

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

이처럼 String 타입에 extension을 만들어주면, strikeThrough() 메소드를 불러오기만 하면 되더라!!

어떤 식으로 사용했냐면..

self.todoTableTitle.attributedText = self.todoTableTitle.text?.strikeThrough()

이런식으로... 사용하면 가능했다!
뭔가 특정 부분에서 구현해야하는 기능이 있다면, 그리고 그 구현을 위한 코드가 꽤 길고 반복적으로 사용된다면 타입에 확장을 하는 방식으로 정리하면 편해질 수 있음을 알았던 것 같다.

profile
iOS 개발자가 되고 싶어요

0개의 댓글