관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] UITextView의 dataDetectorTypes 프로퍼티 (링크거는 방법, NSMutableAttributedString) 본문

iOS 응용 (swift)

[iOS - swift] UITextView의 dataDetectorTypes 프로퍼티 (링크거는 방법, NSMutableAttributedString)

jake-kim 2022. 2. 19. 02:14

 

UITextView에 링크거는 방법

UITextView에서 링크 걸기

  • dataDetectorTypes = .link 옵션을 주어서 링크 활성화
  • isEditable도 false로 설정하면, text에 링크가 있으면 자동으로 링크가 자동으로 설정
private lazy var textView: UITextView = {
  let view = UITextView()
  view.text = "링크: https://ios-development.tistory.com/"
  view.dataDetectorTypes = .link
  view.isEditable = false
  return view
}()
  • 클릭하면 자동으로 safari로 이동
    • 하이퍼 링크로 이동될 때 따로 `UIApplication.shared.open(url)`와 같은 코드가 필요 없는 장점이 존재

attributedText로 링크 걸기

  • attributedString에 link속성을 넣어서 UITextView의 attributedString값에 대입하면 자동으로 링크 연결 가능
    extension NSMutableAttributedString {
      public func linked(text: String, url: String) {
        let foundRange = self.mutableString.range(of: text)
        if foundRange.location != NSNotFound {
          self.addAttribute(.link, value: url, range: foundRange)
        }
      }
    }
    
    private lazy var textView: UITextView = {
      let view = UITextView()
      let attributedString = NSMutableAttributedString(string: "블로그 링크")
      attributedString.linked(text: "링크", url: "https://ios-development.tistory.com/")
      view.attributedText = attributedString
      view.dataDetectorTypes = .link
      view.isEditable = false
      return view
    }()​

* 전체 코드

import UIKit

class ViewController: UIViewController {
  private lazy var textView: UITextView = {
    let view = UITextView()
    let attributedString = NSMutableAttributedString(string: "블로그 링크")
    attributedString.linked(text: "링크", url: "https://ios-development.tistory.com/")
    view.attributedText = attributedString
    view.dataDetectorTypes = .link
    view.isEditable = false
    return view
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    self.view.addSubview(self.textView)
    self.textView.translatesAutoresizingMaskIntoConstraints = false
    self.textView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 56).isActive = true
    self.textView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -56).isActive = true
    self.textView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 120).isActive = true
    self.textView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -120).isActive = true
  }
}

extension NSMutableAttributedString {
  public func linked(text: String, url: String) {
    let foundRange = self.mutableString.range(of: text)
    if foundRange.location != NSNotFound {
      self.addAttribute(.link, value: url, range: foundRange)
    }
  }
}
Comments