iOS 응용 (swift)
[iOS - swift] UIButton underline 설정 방법
jake-kim
2021. 10. 27. 23:59

NSMutableAttributedString
- 텍스트 + 속성값을 가지고 있는 인스턴스
- 속성값: 텍스트 색상, 폰트, 하이퍼링크 등 속성 값을 가지고 있는 String 인스턴스

사용 방법
- NSMutableAttributedString 인스턴스를 만든 후, 해당 인스턴스에 underlineStyle 속성을 추가하고, UIButton.setAttributedTitle()로 만든 인스턴스 주입
- extension UIButton으로 구현
extension UIButton {
// 구현
}
- UIButton의 title 획득
guard let title = title(for: .normal) else { return }
- NSMutableAttributedString 인스턴스 획득
let attributedString = NSMutableAttributedString(string: title)
- 인스턴스에 속성 추가
- `underlineStyle` 속성
attributedString.addAttribute(.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: title.count)
- UIButton 인스턴스에 NSMutableAttributedString 적용
setAttributedTitle(attributedString, for: .normal)
- 전체 코드
extension UIButton {
func setUnderline() {
guard let title = title(for: .normal) else { return }
let attributedString = NSMutableAttributedString(string: title)
attributedString.addAttribute(.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: title.count)
)
setAttributedTitle(attributedString, for: .normal)
}
}
- 사용하는 쪽
let button = uibutton()
button.setUnderline()