UITextView에서 자동 감지 링크의 색상을 변경할 수 있습니까?
UITextView
전화 번호와 링크를 감지 하는 을 가지고 있지만 이것은 내를 무시 fontColor
하고로 변경합니다 blueColor
. 자동 감지 링크의 색상을 포맷하는 방법이 있습니까, 아니면이 기능의 수동 버전을 시도해야합니까?
iOS 7에서는 tintColor
의를 설정할 수 있습니다 UITextView
. 커서 색상과 선택한 텍스트 색상뿐만 아니라 링크 색상에도 영향을줍니다.
아이폰 OS 7은 또한에 새 속성 추가 UITextView
라는 linkTextAttributes
완전히 링크 스타일을 제어 할 수 있도록 나타납니다.
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];
UIAppearance
프로토콜을 사용 하여 모든 텍스트보기에 변경 사항을 적용 할 수 있습니다.
스위프트 4.x :
UITextView.appearance().linkTextAttributes = [ .foregroundColor: UIColor.red ]
스위프트 3.x :
UITextView.appearance().linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.red ]
스위프트 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:)
코드를 호출하는 것이 좋습니다.
TextView에서 하이퍼 링크 색상을 다음과 같이 변경할 수 있습니다.
펜촉 파일에서 속성 창으로 이동하여 색조를 원하는 색상으로 변경할 수 있습니다.
또는 아래 코드를 사용하여 프로그래밍 방식으로 수행 할 수도 있습니다
[YOURTEXTVIEW setTintColor:[UIColor whiteColor]];
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 = [:]
틴트 컬러는 스토리 보드에서도 가능합니다.
웹뷰를 사용하지 않고 실제로 다른 방법 을 찾았 지만 개인 API를 사용 하며 앱 스토어에서 거부 될 수 있음 을 명심하십시오 .
편집 : 개인 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];
}
}
편집 : 음주로하지 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;
}
이제 'headercopy'클래스를 다음과 같이 html 페이지에 사용하십시오.
<b>Fax:</b><a href="tel:646.200.7535" class="headercopy"> 646-200-7535</a><br />
클릭 기능에 필요한 색상으로 전화 번호가 표시됩니다.
이 코드는 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 0232 963 959</a></div>
'developer tip' 카테고리의 다른 글
ESLint 구문 분석 오류 : 예기치 않은 토큰 (0) | 2020.07.28 |
---|---|
스핀 락 대 세마포어 (0) | 2020.07.28 |
1970 년 이후 DateTime을 초 단위로 변환하려면 어떻게해야합니까? (0) | 2020.07.28 |
이 jQuery 클릭 기능이 작동하지 않는 이유는 무엇입니까? (0) | 2020.07.28 |
.exe 파일 이름으로 일부 프로세스 종료 (0) | 2020.07.28 |