UITextView에서 자동 감지 된 링크의 색상을 변경할 수 있습니까?


115

나는 UITextView전화 번호와 링크를 감지 하는 것이 있었지만 이것은 내를 재정의 fontColor하고 blueColor. 자동 감지 된 링크의 색상을 형식화하는 방법이 있습니까? 아니면이 기능의 수동 버전을 시도해야합니까?


private-api subview UIWebDocumentView를 사용하여이 답변을 확인하십시오. stackoverflow.com/a/11745983/111277
— situee

답변:


170

iOS 7 tintColor에서는 UITextView. 링크 색상, 커서 라인 및 선택한 텍스트 색상에 영향을줍니다.

iOS 7은 또한 링크 스타일을 완전히 제어 할 수있는 것처럼 보이는 새로운 속성을 UITextViewcalled에 추가했습니다 linkTextAttributes.


2
이 답변에 대한 추가 설명을 제공했습니다. stackoverflow.com/a/21027340/1202222
— Tim Windsor Brown

아이폰 OS 10.3에서 나는 재정의 할 수 없습니다 NSFontAttributeName와 함께 linkTextAttributes. 나는 나의NSLinkAttributeName
— Heath Borders

37

UITextView를 사용하는 대신 UIWebView를 사용하고 "자동 감지 링크"를 활성화했습니다. 링크 색상을 변경하려면 태그에 대한 일반 CSS를 생성했습니다.

나는 다음과 같은 것을 사용했습니다.

NSString * htmlString = [NSString stringWithFormat:@"<html><head><script> document.ontouchmove = function(event) { if (document.body.scrollHeight == document.body.clientHeight) event.preventDefault(); } </script><style type='text/css'>* { margin:0; padding:0; } p { color:black; font-family:Helvetica; font-size:14px; } a { color:#63B604; text-decoration:none; }</style></head><body><p>%@</p></body></html>", [update objectForKey:@"text"]];
webText.delegate = self;
[webText loadHTMLString:htmlString baseURL:nil];

13
이것은 그러한 간단한 작업에 대해 매우 끔찍한 것처럼 보입니다.
— yuikonnu

알아 ...하지만 덜 해킹 된 해결 방법은 없습니다. 애플은이 작은 세부 사항에 대해 정말로 생각해야합니다.
— Leandro Alves 2013 년

@Oscar 글쎄, Alexanders의 대답보다 덜 hackish라고 생각합니다. 이러한 기본 기능에 대한 단순한 속성이 없다는 사실은 여전히 ​​미쳤습니다.
— Andy

1
질문은 webview가 아닌 ​​textview에 관한 것입니다!
— Boris Gafurov 2013 년

"asdasd"에 완전히 동의합니다. 웹 접근 방식은 매우 비싸며 얼마나 많은 램을 사용하는지 확인합니다. 이러한 간단한 작업에는 Apple이 제공하는 textview 및 속성을 사용하십시오.
— ingconti

37

UIAppearance프로토콜을 사용 하여 모든 텍스트보기에 변경 사항을 적용 할 수 있습니다.

Swift 4.x :

UITextView.appearance().linkTextAttributes = [ .foregroundColor: UIColor.red ]

Swift 3.x :

UITextView.appearance().linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.red ]

Swift 2.x :

UITextView.appearance().linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.redColor() ]

목표 -C :

[UITextView appearance].linkTextAttributes = @{ NSForegroundColorAttributeName : UIColor.redColor };

의 모양 UITextView은 문서화되어 있지 않지만 잘 작동합니다.

마음에 계속 UIAppearance주의 사항 :

iOS는보기가 창에 들어갈 때 모양 변경을 적용하지만 이미 창에있는보기의 모양은 변경하지 않습니다. 현재 창에있는보기의 모양을 변경하려면보기 계층 구조에서보기를 제거한 다음 다시 넣으십시오.

즉 init(), 또는 init(coder:)메서드 에서이 코드를 호출하면 UI 개체 모양 이 변경되지만에서 loadView()또는 viewDidLoad()viewController를 호출 하면 .
전체 응용 프로그램의 모양을 설정하려면 application(_:didFinishLaunchingWithOptions:)이러한 코드를 호출하는 것이 좋습니다.


내가 커서 / 텍스트 선택 및 링크에 대해 다른 색 사용하기 원하는 나는, 선택한 답변을 통해이 일을 선호
— 케빈 R

이것은 가장 최신의 답변입니다.
— yuzer

UITextView를 사용하고 viewdidload에서 위의 코드를 작성했습니다. 하지만 텍스트 필드에 이메일을 쓰고 공백을 입력하면 색상이 변경되지 않습니다.
— Raj Aggrawal 2016 년

18

UITextView의 문제점 linkTextAttributes은 자동으로 감지 된 모든 링크에 적용된다는 것입니다. 다른 링크가 다른 속성을 갖도록하려면 어떻게해야합니까?

트릭이있는 것으로 밝혀졌습니다. 링크를 텍스트 뷰의 속성 텍스트의 일부로 구성 하고 linkTextAttributes를 빈 사전으로 설정하는 것 입니다.

다음은 iOS 11 / Swift 4의 예입니다.

// mas is the mutable attributed string we are forming...
// ... and we're going to use as the text view's `attributedText`
mas.append(NSAttributedString(string: "LINK", attributes: [
    NSAttributedStringKey.link : URL(string: "https://www.apple.com")!,
    NSAttributedStringKey.foregroundColor : UIColor.green,
    NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
]))
// ...
self.tv.attributedText = mas
// this is the important thing:
self.tv.linkTextAttributes = [:]

내 문자열은 "iOS를 배우고 싶습니까?"입니다. 최고의 무료 iOS 튜토리얼 소스를 방문해야합니다! Swift check hello google.com Attributed 9826012345 String testing in on going ... "및 기본 링크 속성은 웹 링크 및 휴대 전화 번호에 필요합니다.하지만 문자열 부분"iOS를 배우고 싶습니까? "다른 색상으로 링크를 만들고 싶습니다. [:]은 사용자 정의 링크를 위해 일하고 link..So self.tv.linkTextAttributes =이와.
— BalKrishan 야다 브

14

다음과 같이 TextView에서 하이퍼 링크 색상을 변경할 수 있습니다.

Nib 파일에서 속성 창으로 이동하여 원하는 색상으로 색조를 변경할 수 있습니다.

또는 아래 코드를 사용하여 프로그래밍 방식으로 수행 할 수도 있습니다.

[YOURTEXTVIEW setTintColor:[UIColor whiteColor]];


3

webview를 사용하지 않고 실제로 다른 방법 을 찾았 지만 비공개 API를 사용 하고 appstore에서 거부 될 수 있음 을 명심하십시오 .

편집 : 개인 API 사용이 있지만 내 앱이 사과에 의해 승인되었습니다!

먼저 메서드를 사용하여 UITextView에 범주를 선언하십시오.

- (id)contentAsHTMLString;
- (void)setContentToHTMLString:(id)arg1;

그들은 다음을 수행하고 있습니다.

- (id)contentAsHTMLString;
{
    return [super contentAsHTMLString];
}

- (void)setContentToHTMLString:(id)arg1;
{
    [super setContentToHTMLString:arg1];
}

이제 다채로운 링크에 대한 방법을 작성하십시오.

- (void) colorfillLinks;
{
    NSString *contentString = [self.textViewCustomText contentAsHTMLString];
    contentString = [contentString stringByReplacingOccurrencesOfString:@"x-apple-data-detectors=\"true\""
                                         withString:@"x-apple-data-detectors=\"true\" style=\"color:white;\""];
    [self.textViewCustomText setContentToHTMLString:contentString];
}

모든 유형의 링크에서 특정 색상으로 스타일 속성을 설정합니다.

UITextView는 div를 통해 Webiview로 렌더링되므로 더 나아가서 각 링크 유형을 개별적으로 색칠 할 수도 있습니다.

<div><a href="http://www.apple.com" x-apple-data-detectors="true" style="color:white;" x-apple-data-detectors-type="link" x-apple-data-detectors-result="0">http://www.apple.com</a></div>

는 x-apple-data-detectors-type="link"링크의 정확한 유형에 대한 지표이다

편집하다

에 iOS7이가 더 이상 작동하지 않습니다. iOS7에서는 색조 색상을 설정하여 UITextViews의 링크 색상을 쉽게 변경할 수 있습니다. 당신은 전화해서는 안됩니다

- (id)contentAsHTMLString;

더 이상 예외가 발생합니다. iOS 7 이하를 지원하려면 대신 다음을 수행하십시오.

- (void) colorfillLinks;
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
    self.tintColor = [UIColor colorWithRed:79.0/255.0
                                     green:168.0/255.0
                                      blue:224.0/255.0
                                     alpha:1.0];
} else if(![self isFirstResponder ]) {
    NSString *contentString = [self contentAsHTMLString];
    contentString = [contentString stringByReplacingOccurrencesOfString:@"x-apple-data-detectors=\"true\""
                                                             withString:@"x-apple-data-detectors=\"true\" style=\"color:#DDDDDE;\""];
    [self setContentToHTMLString:contentString];

}
}

3

스위프트 5 답변

멋지고 간단

myTextView.linkTextAttributes = [.foregroundColor: UIColor.white]

0

편집 : 대신 UITextView사용 하지 마십시오 UIWebView.

이를 위해 스타일 시트를 만들어야합니다. 필요한 색상 조합으로 클래스를 정의하십시오.

.headercopy {
 font-family: "Helvetica";
 font-size: 14px;
 line-height: 18px;
 font-weight:bold;
 color: #25526e;
}
a.headercopy:link {
 color:#ffffff;
 text-decoration:none;
}
a.headercopy:hover {
 color:#00759B;
 text-decoration:none;
}
a.headercopy:visited {
 color:#ffffff;
 text-decoration:none;
} 
a.headercopy:hover {
 color:#00759B;
 text-decoration:none;
}

이제 다음과 같이 html 페이지에 'headercopy'클래스를 사용하십시오.

<b>Fax:</b><a href="tel:646.200.7535" class="headercopy"> 646-200-7535</a><br />

클릭 기능에 필요한 색상으로 전화 번호가 표시됩니다.


웹 뷰를 사용하는 것은 네이티브 앱에 나쁜 프로그래밍 스타일입니다.
— ingconti

0

이 코드는 I-Phone에서 전화 번호의 색상을 설정하지만 자동 통화 링크는 무효화됩니다.

<div><a href="#" x-apple-data-detectors="true" style="color:white;" x-apple-data-detectors-type="link" x-apple-data-detectors-result="0">p&nbsp;&nbsp;0232 963 959</a></div>

0

이것이 제가 Swift 5를 사용한 방법입니다.

let attributedString = NSMutableAttributedString(string: myTextView.text ?? "")
myTextView.linkTextAttributes = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.whiteColor] as [NSAttributedString.Key: Any]?
myTextView.attributedText = attributedString
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.