NSAttributedString에서 클릭 가능한 링크를 작성하려면 어떻게 해야 합니까?
할 수 있도록 UITextViewIB 뷰에서 "detect links" 체크박스를 설정하면 HTTP 링크가 검출되어 하이퍼링크로 바뀝니다.
그러나 이는 사용자에게 표시되는 링크가 "원시" 링크임을 의미합니다.RTF 파일과 HTML 모두 사용자가 읽을 수 있는 문자열에 링크를 설정할 수 있습니다.
뷰 텍스트 뷰)에 귀속 할 수 UILabel ★★★★★★★★★★★★★★★★★」UITextField그에서는 (된 되어 있는 할 수 없습니다.
수 있는 할 수 있도록 하는 ?UITextView,UILabel ★★★★★★★★★★★★★★★★★」UITextField
SO에 대한 표시는 다르지만, 대략적인 생각은 다음과 같습니다.제가 원하는 것은 다음과 같은 문자입니다.
내가 얻을 수 있는 건 이것뿐이야
이 모프는 Face Dancer에서 생성되었습니다. 앱스토어에서 보려면 http://example.com/facedancer을 클릭하십시오.
NSMutableAttributedString을 사용합니다.
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"Google"];
[str addAttribute: NSLinkAttributeName value: @"http://www.google.com" range: NSMakeRange(0, str.length)];
yourTextView.attributedText = str;
편집:
하는 것이 하기 입니다.UITextField ★★★★★★★★★★★★★★★★★」UILabel는, 의 을 서포트하고 않습니다.URL 은 오픈 URL 을 하고 있지 않습니다.「 」를 사용하고 UILabel링크를 사용하여 TTTttributed Label을 체크할 수 있습니다.
,, 정, 정, 정, 정, 세로 설정해야 합니다.dataDetectorTypesUITextView로로 합니다.UIDataDetectorTypeLink ★★★★★★★★★★★★★★★★★」UIDataDetectorTypeAll를 、 URL 、 。또는 댓글에 제시된 대로 위임 방법을 사용할 수 있습니다.
곳에서 NSMutableAttributedString:
스위프트 3
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(.link, value: linkURL, range: foundRange)
return true
}
return false
}
}
스위프트 2
import Foundation
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.rangeOfString(textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
return true
}
return false
}
}
사용 예:
let attributedString = NSMutableAttributedString(string:"I love stackoverflow!")
let linkWasSet = attributedString.setAsLink("stackoverflow", linkURL: "http://stackoverflow.com")
if linkWasSet {
// adjust more attributedString properties
}
목표-C
순수한 Objective-C 프로젝트에서 동일한 작업을 수행해야 하는 요건을 충족했습니다. 따라서 Objective-C 카테고리가 있습니다.
@interface NSMutableAttributedString (SetAsLinkSupport)
- (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL;
@end
@implementation NSMutableAttributedString (SetAsLinkSupport)
- (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL {
NSRange foundRange = [self.mutableString rangeOfString:textToFind];
if (foundRange.location != NSNotFound) {
[self addAttribute:NSLinkAttributeName value:linkURL range:foundRange];
return YES;
}
return NO;
}
@end
사용 예:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:"I love stackoverflow!"];
BOOL linkWasSet = [attributedString setAsLink:@"stackoverflow" linkURL:@"http://stackoverflow.com"];
if (linkWasSet) {
// adjust more attributedString properties
}
NSTextField의 Behavior 속성이 Selectable로 설정되어 있는지 확인합니다.
이러한 사용 사례에 특별히 대처하기 위해 UILabel의 하위 클래스를 만들었습니다.여러 링크를 쉽게 추가하고 해당 링크에 대해 서로 다른 핸들러를 정의할 수 있습니다.터치 피드백 시 누름 링크를 강조 표시할 수도 있습니다.https://github.com/null09264/FRHyperLabel 를 참조해 주세요.
이 경우 코드는 다음과 같습니다.
FRHyperLabel *label = [FRHyperLabel new];
NSString *string = @"This morph was generated with Face Dancer, Click to view in the app store.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
[label setLinkForSubstring:@"Face Dancer" withLinkHandler:^(FRHyperLabel *label, NSString *substring){
[[UIApplication sharedApplication] openURL:aURL];
}];
샘플 스크린샷(이 경우 URL을 열지 않고 경보를 팝업하도록 핸들러가 설정됨)

ujell 솔루션의 작은 개선점:NSString 대신 NSURL을 사용하는 경우 임의의 URL(커스텀 URL 등)을 사용할 수 있습니다.
NSURL *URL = [NSURL URLWithString: @"whatsapp://app"];
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"start Whatsapp"];
[str addAttribute: NSLinkAttributeName value:URL range: NSMakeRange(0, str.length)];
yourTextField.attributedText = str;
재미있게 보내!
Swift 4:
var string = "Google"
var attributedString = NSMutableAttributedString(string: string, attributes:[NSAttributedStringKey.link: URL(string: "http://www.google.com")!])
yourTextView.attributedText = attributedString
Swift 3.1:
var string = "Google"
var attributedString = NSMutableAttributedString(string: string, attributes:[NSLinkAttributeName: URL(string: "http://www.google.com")!])
yourTextView.attributedText = attributedString
저도 비슷한 요건이 있어서 처음에는 UILabel을 사용하다가 UITextView가 더 낫다는 것을 알게 되었습니다.시키고 UITextView의 메서드를 .NSMutableAttributedString(+1) c 입니다.
-(void)setTextAsLink:(NSString*) textToFind withLinkURL:(NSString*) url
{
NSRange range = [self.mutableString rangeOfString:textToFind options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[self addAttribute:NSLinkAttributeName value:url range:range];
[self addAttribute:NSForegroundColorAttributeName value:[UIColor URLColor] range:range];
}
}
다음 대리인을 사용하여 작업을 처리할 수 있습니다.
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange
{
// do the task
return YES;
}
클릭 가능한 링크를 지원하는 UITextView를 사용합니다.다음 코드를 사용하여 속성 문자열 생성
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];
다음으로 다음과 같이 UITextView텍스트를 설정합니다.
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],
NSUnderlineColorAttributeName: [UIColor blueColor],
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
XIB에서 UITextView의 "Selectable" 동작을 활성화해야 합니다.
UILabel UITextView 。★★★★★★★★★★★★★★★★★를 유효하게 할 필요가 있습니다.Selectable를 무효로 합니다.Editable.
그런 다음 스크롤 표시기와 바운스를 비활성화합니다.


★★★★★★★★★★★★★★★를 사용한 솔루션NSMutableAttributedString string html " " " " "NSHTMLTextDocumentType
NSString *s = @"<p><a href='https://itunes.apple.com/us/app/xxxx/xxxx?mt=8'>https://itunes.apple.com/us/app/xxxx/xxxx?mt=8</a></p>";
NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
initWithData: [s dataUsingEncoding:NSUnicodeStringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes: nil
error: nil
];
cell.content.attributedText = text;
질문의 핵심은 텍스트를 조작하고 링크를 추가하는 커스텀 코드를 작성하지 않고도 텍스트 뷰/필드/라벨에 클릭 가능한 링크를 만들 수 있기를 원한다는 것입니다.데이터 중심이었으면 좋겠다고 생각했습니다.
드디어 방법을 알아냈어요.문제는 IB가 임베디드 링크를 지원하지 않는다는 것입니다.
iOS 「Dada」iOS 은전 。NSAttributedString에서는, RTF 파일로부터 어트리뷰트 문자열을 초기화할 수 없습니다. X 의 OS X 。NSAttributedString 에는 RTF 파일을 입력으로 사용하는 이니셜라이저가 있습니다.
NSAttributedString하므로 NSDataNSadding/NSData로할 수 .
RTF 파일을 입력으로 사용하여 NSData를 포함하는 .data 확장자를 가진 파일을 NSData에서 출력하는 OS X 명령줄 도구를 만들었습니다.그런 다음 .data 파일을 프로젝트에 넣고 텍스트를 보기에 로드하는 코드 몇 줄을 추가합니다.코드는 다음과 같습니다(이 프로젝트는 Swift에 있습니다).
/*
If we can load a file called "Dates.data" from the bundle and convert it to an attributed string,
install it in the dates field. The contents contain clickable links with custom URLS to select
each date.
*/
if
let datesPath = NSBundle.mainBundle().pathForResource("Dates", ofType: "data"),
let datesString = NSKeyedUnarchiver.unarchiveObjectWithFile(datesPath) as? NSAttributedString
{
datesField.attributedText = datesString
}
포맷된 텍스트를 많이 사용하는 앱의 경우 특정 폴더의 모든 .rtf 파일이 원본이고 .data 파일이 출력임을 Xcode에 알려주는 빌드 규칙을 만듭니다.이렇게 하면 지정된 디렉토리에 .rtf 파일을 추가하거나 기존 파일을 편집하면 빌드 프로세스에서 새 파일인지 확인하고 명령줄 도구를 실행하여 해당 파일을 앱 번들에 복사할 수 있습니다.그것은 아름답게 작동한다.
기술을 시연하는 샘플(Swift) 프로젝트에 링크한 블로그 투고를 작성했습니다.여기서 보실 수 있습니다.
앱에서 열리는 UITextField에서 클릭 가능한 URL 만들기
Swift 3 예: 속성 텍스트 탭에 대한 작업을 탐지합니다.
https://stackoverflow.com/a/44226491/5516830
let termsAndConditionsURL = TERMS_CONDITIONS_URL;
let privacyURL = PRIVACY_URL;
override func viewDidLoad() {
super.viewDidLoad()
self.txtView.delegate = self
let str = "By continuing, you accept the Terms of use and Privacy policy"
let attributedString = NSMutableAttributedString(string: str)
var foundRange = attributedString.mutableString.range(of: "Terms of use") //mention the parts of the attributed text you want to tap and get an custom action
attributedString.addAttribute(NSLinkAttributeName, value: termsAndConditionsURL, range: foundRange)
foundRange = attributedString.mutableString.range(of: "Privacy policy")
attributedString.addAttribute(NSLinkAttributeName, value: privacyURL, range: foundRange)
txtView.attributedText = attributedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "WebView") as! SKWebViewController
if (URL.absoluteString == termsAndConditionsURL) {
vc.strWebURL = TERMS_CONDITIONS_URL
self.navigationController?.pushViewController(vc, animated: true)
} else if (URL.absoluteString == privacyURL) {
vc.strWebURL = PRIVACY_URL
self.navigationController?.pushViewController(vc, animated: true)
}
return false
}
로 Wise에서도 액션을 할 수 .shouldInteractWith URL[ UIText Field Delegate ](UITextFieldDelegate " 。
건배!!
특정 url(urlString)을 가진 문자열(fullString)에 링크(linkString)를 추가하는 메서드를 작성했습니다.
- (NSAttributedString *)linkedStringFromFullString:(NSString *)fullString withLinkString:(NSString *)linkString andUrlString:(NSString *)urlString
{
NSRange range = [fullString rangeOfString:linkString options:NSLiteralSearch];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:fullString];
NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{NSForegroundColorAttributeName:RGB(0x999999),
NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Light" size:10],
NSParagraphStyleAttributeName:paragraphStyle};
[str addAttributes:attributes range:NSMakeRange(0, [str length])];
[str addAttribute: NSLinkAttributeName value:urlString range:range];
return str;
}
이렇게 불러야 합니다.
NSString *fullString = @"A man who bought the Google.com domain name for $12 and owned it for about a minute has been rewarded by Google for uncovering the flaw.";
NSString *linkString = @"Google.com";
NSString *urlString = @"http://www.google.com";
_youTextView.attributedText = [self linkedStringFromFullString:fullString withLinkString:linkString andUrlString:urlString];
탭 인식기(여기서 malex의 응답에 근거한 UILABEL의 문자 인덱스)로 불리는 순수 UILABEL을 계속 사용할 필요가 있었습니다.
UILabel* label = (UILabel*)gesture.view;
CGPoint tapLocation = [gesture locationInView:label];
// create attributed string with paragraph style from label
NSMutableAttributedString* attr = [label.attributedText mutableCopy];
NSMutableParagraphStyle* paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.alignment = label.textAlignment;
[attr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.attributedText.length)];
// init text storage
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attr];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
// init text container
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(label.frame.size.width, label.frame.size.height+100) ];
textContainer.lineFragmentPadding = 0;
textContainer.maximumNumberOfLines = label.numberOfLines;
textContainer.lineBreakMode = label.lineBreakMode;
[layoutManager addTextContainer:textContainer];
// find tapped character
NSUInteger characterIndex = [layoutManager characterIndexForPoint:tapLocation
inTextContainer:textContainer
fractionOfDistanceBetweenInsertionPoints:NULL];
// process link at tapped character
[attr enumerateAttributesInRange:NSMakeRange(characterIndex, 1)
options:0
usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
if (attrs[NSLinkAttributeName]) {
NSString* urlString = attrs[NSLinkAttributeName];
NSURL* url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
}
}];
UITextView를 사용하여 dataDetector를 설정합니다.링크 유형.
다음과 같습니다.
testTextView.editable = false
testTextView.dataDetectorTypes = .link
링크, 전화번호, 주소 등을 검출하는 경우그리고나서
testTextView.dataDetectorTypes = .all
UITextView용 코드 프리 솔루션을 찾으십시오.
검출을 유효하게 하다-> 링크 옵션, URL 및 이메일이 검출되어 클릭할 수 있게 됩니다.
업데이트:
제 질문에는 두 가지 중요한 부분이 있었습니다.
- 클릭 가능한 링크에 대해 표시된 텍스트가 실제 호출된 링크와 다른 링크를 만드는 방법:
- 텍스트의 속성을 설정하기 위해 커스텀코드를 사용하지 않고 링크를 설정하는 방법.
은 iOS 7에서 를 로드하는 한 것으로 .NSData.
스스classclassclassclassclassclassclassclassclassclassclassclass의 .UITextView이 기능을 이용하여@IBInspectableRTF의 IB입니다.파일명을 IB에 입력하기만 하면 나머지는 커스텀클래스로 처리됩니다.
자세한 내용은 다음과 같습니다.
7의 경우 iOS 7의 경우NSAttributedString을 initWithData:options:documentAttributes:error:NSData NSAttributedString 이이 。을 NSData에한 후 NSData RTF를 사용할 수 .initWithData:options:documentAttributes:error:NSDATA의 경우 (메서드(메서드)도initWithFileURL:options:documentAttributes:error:. 하는 합니다.initWithData:options:documentAttributes:error:더 이상 사용되지 않았습니다.
사용하고 있는 링크에 고유의 코드를 작성하지 않고 클릭 가능한 링크를 텍스트 뷰에 인스톨 할 수 있는 방법이 필요했습니다.
이었습니다.UITextView는 UITextView를 호출합니다.RTF_UITextView그리고 그것을 위해@IBInspectable property called라고 하는 RTF_Filename를 합니다.@IBInspectableInterface Builder" "Attributes Inspector" 입니다.IB wihtout 。
@IBDesignable커스텀 클래스 덕분입니다.@IBDesignable 해, 뷰가 있는 ) 공교롭게도는, 「Xcode」가 .@IBDesignable하여 뷰 가능한 수 .)처음 추가했을 때는 정상적으로 동작했지만, 텍스트 뷰의 플레인 텍스트 내용을 삭제했기 때문에 클릭 가능한 링크가 없어져 되돌릴 수 없었습니다.)
의 ★★★의 RTF_UITextView매우 간단합니다.「 」의 에 가세해, 「 」의 추가에 가세하고 .@IBDesignable와 Atribute는RTF_Filename「」가 @IBInspectabledidSet()의 메서드RTF_Filename★★★★★★★★★★★★★★★★★.didSet()는 메서드의 마다 호출됩니다.RTF_Filename속성이 변경됩니다.의 didSet()방법은 매우 간단합니다.
@IBDesignable
class RTF_UITextView: UITextView
{
@IBInspectable
var RTF_Filename: String?
{
didSet(newValue)
{
//If the RTF_Filename is nil or the empty string, don't do anything
if ((RTF_Filename ?? "").isEmpty)
{
return
}
//Use optional binding to try to get an URL to the
//specified filename in the app bundle. If that succeeds, try to load
//NSData from the file.
if let fileURL = NSBundle.mainBundle().URLForResource(RTF_Filename, withExtension: "rtf"),
//If the fileURL loads, also try to load NSData from the URL.
let theData = NSData(contentsOfURL: fileURL)
{
var aString:NSAttributedString
do
{
//Try to load an NSAttributedString from the data
try
aString = NSAttributedString(data: theData,
options: [:],
documentAttributes: nil
)
//If it succeeds, install the attributed string into the field.
self.attributedText = aString;
}
catch
{
print("Nerp.");
}
}
}
}
}
@IBDesignable 속성에서 스타일 텍스트를 인터페이스 빌더에서 미리 볼 수 없는 경우 위의 코드를 커스텀서브클래스가 아닌 UITextView의 확장자로 설정하는 것이 좋을 수 있습니다.이렇게 하면 텍스트 보기를 사용자 정의 클래스로 변경하지 않고도 텍스트 보기에서 사용할 수 있습니다.
iOS 7 이전 버전을 지원해야 하는 경우 다른 답변을 참조하십시오.
gitHub에서 이 새로운 클래스를 포함하는 샘플 프로젝트를 다운로드할 수 있습니다.
Github에서의 DatesInSwift 데모 프로젝트
Swift 버전:
// Attributed String for Label
let plainText = "Apkia"
let styledText = NSMutableAttributedString(string: plainText)
// Set Attribuets for Color, HyperLink and Font Size
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSLinkAttributeName:NSURL(string: "http://apkia.com/")!, NSForegroundColorAttributeName: UIColor.blueColor()]
styledText.setAttributes(attributes, range: NSMakeRange(0, plainText.characters.count))
registerLabel.attributedText = styledText
위의 @Karl Nosworthy 및 @esilver에 문제가 있는 경우 NSMutable Attributed String 확장을 Swift 4 버전으로 업데이트했습니다.
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
_ = NSMutableAttributedString(string: textToFind)
// Set Attribuets for Color, HyperLink and Font Size
let attributes = [NSFontAttributeName: UIFont.bodyFont(.regular, shouldResize: true), NSLinkAttributeName:NSURL(string: linkURL)!, NSForegroundColorAttributeName: UIColor.blue]
self.setAttributes(attributes, range: foundRange)
return true
}
return false
}
}
Duncan C의 IB 동작에 대한 원래 설명에 간단하게 추가.그는 다음과 같이 쓰고 있습니다.UITextView에서 하이퍼링크를 클릭할 수 있도록 하는 것은 간단한 일입니다.IB 뷰에서 "detect links" 체크박스를 설정하면 http 링크가 검색되어 하이퍼링크로 바뀝니다.
(적어도 xcode 7에서는) URL을 검출하고 클릭하기 위해서는 편집 가능한 동작도 해제해야 합니다.
Swift 5.5에서는
Swift 5.5 NSAttributed String은 완전히 현지화가 가능하며 문자 수조차 정의하지 않고 사용하기 쉽습니다.
func attributedStringBasics(important: Bool) {
var buy = AttributedString("Buy a new iPhone!")
buy.font = .body.bold()
var website = AttributedString("Visit Apple")
website.font = .body.italic()
website.link = URL(string: "http://www.apple.com")
var container = AttributeContainer()
if important {
container.foregroundColor = .red
container.underlineColor = .primary
} else {
container.foregroundColor = .primary
}
buy.mergeAttributes(container)
website.mergeAttributes(container)
print(buy)
print(website)
}
@AliOHAttributedStringAdditions Software의 뛰어난 라이브러리로 링크를 쉽게 추가할 수 있습니다.UILabel다음은 매뉴얼입니다.https://github.com/AliSoftware/OHAttributedStringAdditions/wiki/link-in-UILabel
UITextView에서 NSLinkAttributeName을 사용하는 경우 Attributed를 사용하는 것을 고려할 수 있습니다.TextView라이브러리UITextView 서브클래스로 이러한 작업을 매우 쉽게 처리할 수 있습니다.상세한 것에 대하여는, https://github.com/evermeer/AttributedTextView 를 참조해 주세요.
텍스트의 모든 부분을 다음과 같이 상호 작용할 수 있습니다(여기서 textView1은 UITextView IBoutlet).
textView1.attributer =
"1. ".red
.append("This is the first test. ").green
.append("Click on ").black
.append("evict.nl").makeInteract { _ in
UIApplication.shared.open(URL(string: "http://evict.nl")!, options: [:], completionHandler: { completed in })
}.underline
.append(" for testing links. ").black
.append("Next test").underline.makeInteract { _ in
print("NEXT")
}
.all.font(UIFont(name: "SourceSansPro-Regular", size: 16))
.setLinkColor(UIColor.purple)
그리고 해시태그와 언급을 처리하기 위해 다음과 같은 코드를 사용할 수 있습니다.
textView1.attributer = "@test: What #hashtags do we have in @evermeer #AtributedTextView library"
.matchHashtags.underline
.matchMentions
.makeInteract { link in
UIApplication.shared.open(URL(string: "https://twitter.com\(link.replacingOccurrences(of: "@", with: ""))")!, options: [:], completionHandler: { completed in })
}
UITextView에서 액티브한 서브스트링을 원하는 경우 확장 TextView를 사용할 수 있습니다.짧고 단순합니다.원하는 대로 편집할 수 있습니다.
결과:
코드: https://github.com/marekmand/ActiveSubstringTextView
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],
NSUnderlineColorAttributeName: [UIColor blueColor],
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
요점:
- XIB에서 UITextView의 "Selectable" 동작을 활성화해야 합니다.
- XIB에서 UITextView의 "편집 가능" 동작을 비활성화해야 합니다.
언급URL : https://stackoverflow.com/questions/21629784/how-can-i-make-a-clickable-link-in-an-nsattributedstring
'programing' 카테고리의 다른 글
| CSV 파일을 열지 않고 CSV 파일의 행수를 취득할 수 있습니까? (0) | 2023.04.19 |
|---|---|
| ContextMenu를 표시하기 전에 오른쪽 클릭 시 TreeViewNode를 선택합니다. (0) | 2023.04.19 |
| wpf 데이터그램 대체 행 컬러링 (0) | 2023.04.19 |
| int를 선행 0이 있는 문자로 변환하려면 어떻게 해야 합니까? (0) | 2023.04.19 |
| xaml 파일과 xaml.cs 파일을 연결하는 방법 (0) | 2023.04.19 |