Jak mogę utworzyć klikalny link w NSAttributedString?

To trywialne, aby hiperłącza klikalne w UITextView. Po prostu ustawiasz pole wyboru "wykrywaj linki" w widoku w IB, a ono wykrywa linki HTTP i zamienia je w hiperłącza.

Oznacza to jednak, że to, co użytkownik widzi, to link "surowy". Pliki RTF i HTML pozwalają skonfigurować czytelny dla użytkownika ciąg znaków z linkiem " za " nim.

Łatwo jest zainstalować przypisany tekst w widoku tekstowym (lub UILabel lub UITextField, jeśli o to chodzi.) Jednak, gdy ten przypisany tekst zawiera link, nie jest klikalny.

Czy jest sposób, aby tekst czytelny dla użytkownika był klikalny w UITextView, UILabel albo UITextField?

Znaczniki są inne NA SO, ale oto ogólna idea. To co chcę to tekst taki:

Ten morph został wygenerowany za pomocą Face Dancer , Kliknij aby zobaczyć w app store.

Jedyne co mogę dostać to to:

Ten morph został wygenerowany za pomocą Face Dancer, kliknij na http://example.com/facedancer aby wyświetlić w app store.

Author: Tamás Sengel, 2014-02-07

20 answers

Użyj NSMutableAttributedString.

NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"Google"];
[str addAttribute: NSLinkAttributeName value: @"http://www.google.com" range: NSMakeRange(0, str.length)];
yourTextView.attributedText = str;

Edit :

Nie chodzi tu bezpośrednio o pytanie, ale tylko dla wyjaśnienia, UITextField i UILabel nie obsługują otwierania adresów URL. Jeśli chcesz użyć UILabel z linkami, możesz sprawdzić TTTAttributedLabel.

Należy również ustawić dataDetectorTypes wartość twojego UITextView na UIDataDetectorTypeLink lub UIDataDetectorTypeAll, aby otwierać adresy URL po kliknięciu. Możesz też użyć metody delegowania zgodnie z sugestią w komentarzach.

 133
Author: ujell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-27 08:28:02

Uznałem to za bardzo przydatne, ale musiałem to zrobić w kilku miejscach, więc zamknąłem moje podejście w prostym rozszerzeniu do NSMutableAttributedString:

Swift 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
    }
}

Swift 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
   }
}

Przykładowe użycie:

let attributedString = NSMutableAttributedString(string:"I love stackoverflow!")
let linkWasSet = attributedString.setAsLink("stackoverflow", linkURL: "http://stackoverflow.com")

if linkWasSet {
    // adjust more attributedString properties
}

Objective-C

Właśnie spełniłem wymóg, aby zrobić to samo w czystym projekcie Objective-C, więc oto Kategoria 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

Przykładowe użycie:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:"I love stackoverflow!"];

BOOL linkWasSet = [attributedString setAsLink:@"stackoverflow" linkURL:@"http://stackoverflow.com"];

if (linkWasSet) {
    // adjust more attributedString properties
}
 96
Author: Karl Nosworthy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-20 20:38:58

Mała poprawa rozwiązania ujell: jeśli używasz NSURL zamiast NSString, możesz użyć dowolnego adresu URL (np. niestandardowych adresów 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;
Baw się dobrze!
 26
Author: Hans One,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-21 14:07:48

Właśnie stworzyłem podklasę UILabel, aby specjalnie zająć się takimi przypadkami użycia. Możesz łatwo dodać wiele linków i zdefiniować dla nich różne procedury obsługi. Obsługuje również podświetlanie wciśniętego łącza po dotknięciu w celu uzyskania informacji zwrotnej. Proszę odnieść się do https://github.com/null09264/FRHyperLabel .

W Twoim przypadku kod może się podobać:

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];
}];

Przykładowy zrzut ekranu (program obsługi jest ustawiony na wyświetlanie alertu zamiast otwierania adresu url w tym case)

facedancer

 26
Author: Jinghan Wang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-29 15:11:58

Ja też miałem podobny wymóg, początkowo korzystałem z UILabel, a potem zdałem sobie sprawę, że UITextView jest lepszy. Zrobiłem UITextView zachowywać się jak UILabel wyłączając interakcję i przewijanie i zrobiłem metodę kategorii dla NSMutableAttributedString, aby ustawić link do tekstu tak samo, jak to zrobił Karl (+1 za to) to jest moja wersja obj 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];
    }
}

Możesz użyć poniższego delegata do obsługi akcji

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange
{
    // do the task
    return YES;
}
 16
Author: anoop4real,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-31 06:42:07

Użyj UITextView obsługuje klikalne linki. Utwórz przypisany ciąg znaków za pomocą następującego kodu

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];

Następnie Ustaw tekst UITextView w następujący sposób

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],

                                 NSUnderlineColorAttributeName: [UIColor blueColor],

                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;

Upewnij się, że UITextView w XIB jest "wybierany".

 14
Author: Nitheesh George,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-27 08:42:39

Sednem mojego pytania było to, że chciałem mieć możliwość tworzenia klikalnych linków w tekstowych widokach / polach/etykietach bez konieczności pisania kodu niestandardowego, aby manipulować tekstem i dodawać linki. Chciałem, żeby to było oparte na danych.

W końcu wymyśliłem, jak to zrobić. Problem w tym, że IB nie honoruje wbudowanych linków.

Ponadto wersja NSAttributedString na iOS nie pozwala na inicjalizację przypisanego ciągu z pliku RTF. Wersja OS X NSAttributedString czy mA inicjalizator pobierający plik RTF jako wejście.

NSAttributedString jest zgodny z protokołem NSCoding, dzięki czemu można go przekonwertować do / Z NSData

Stworzyłem narzędzie wiersza poleceń systemu OS X, które pobiera plik RTF jako wejście i wyprowadza Plik z rozszerzeniem .dane zawierające NSData z NSCoding. Następnie umieścić .plik danych do mojego projektu i dodać kilka linii kodu, który ładuje tekst do widoku. Kod wygląda tak (ten projekt był w języku 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
}

Dla aplikacji, które używają dużo sformatowanego tekstu, tworzę regułę budowania, która mówi Xcode, że wszystkie .pliki rtf w danym folderze to source i the .Pliki Danych są wyjściem. Kiedy to zrobię, po prostu dodam .pliki rtf do wyznaczonego katalogu (lub edytować istniejące pliki) i proces budowania wykona, że są one nowe/zaktualizowane, uruchamia narzędzie wiersza poleceń i kopiuje pliki do pakietu aplikacji. Działa pięknie.

Napisałem post na blogu, który łączy się z przykładowym (Swift) projektem demonstrującym technikę. Możesz to zobaczyć tutaj:

Tworzenie klikalnych adresów URL w polu UITextField, które otwierają się w Twojej aplikacji

 10
Author: Duncan C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-26 17:01:12

Przykład Swift 3 do wykrywania akcji na przypisanych dotknięciach tekstu

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
}

Podobnie jak wise możesz dodać dowolną akcję za pomocą metody shouldInteractWith URLUITextFieldDelegate.

Zdrówko!!
 8
Author: Akila Wasala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-28 11:17:18

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
 7
Author: Bill Chan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-06 13:13:17

Napisałem metodę, która dodaje link (linkString) do łańcucha (fullString) z określonym adresem url (urlString):

- (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;
}

Powinieneś nazywać to tak:

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];
 4
Author: wzbozon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-16 16:37:30

Wystarczy znaleźć rozwiązanie bez kodu dla UITextView: Tutaj wpisz opis obrazka

Włącz wykrywanie - > opcje linków, URL, a także e-mail zostaną wykryte i klikalne!

 3
Author: Bill Chan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-08 20:06:39

Aktualizacja:

Były 2 kluczowe części mojego pytania:

    Jak zrobić link, w którym tekst wyświetlany dla klikalnego linku jest inny niż rzeczywisty link, który jest wywoływany:]}
  1. Jak skonfigurować linki bez konieczności używania kodu niestandardowego do ustawiania atrybutów w tekście.

Okazuje się, że iOS 7 dodał możliwość ładowania przypisanego tekstu z NSData.

Stworzyłem własną podklasę UITextView, która wykorzystuje atrybut @IBInspectable i pozwala załadować zawartość z pliku RTF bezpośrednio w IB. Po prostu wpisz nazwę pliku do IB, A Klasa niestandardowa zrobi resztę.

Oto szczegóły:

W iOS 7, NSAttributedString zyskał metodę initWithData:options:documentAttributes:error:. Ta metoda pozwala załadować NSAttributedString z obiektu NSData. Możesz najpierw załadować plik RTF do NSData, a następnie użyć initWithData:options:documentAttributes:error:, aby załadować ten plik NSDATA do widoku tekstowego. (Zauważ, że istnieje również metoda initWithFileURL:options:documentAttributes:error:, która załaduje przypisany ciąg bezpośrednio z pliku, ale ta metoda została wycofana w iOS 9. Bezpieczniej jest użyć metody initWithData:options:documentAttributes:error:, która nie była przestarzała.

Chciałem metody, która pozwoli mi zainstalować klikalne linki do moich widoków tekstowych bez konieczności tworzenia kodu specyficznego dla linków, których używałem.

Rozwiązaniem, które wymyśliłem, było stworzenie niestandardowej podklasy UITextView, którą wywołam RTF_UITextView i nadam jej właściwość @IBInspectable o nazwie RTF_Filename. Dodanie atrybutu @IBInspectable do właściwości powoduje, że Interface Builder ujawnia tę właściwość w "Inspektor Atrybutów."Możesz następnie ustawić tę wartość z IB z niestandardowym kodem.

Dodałem również atrybut @IBDesignable do mojej niestandardowej klasy. Atrybut @IBDesignable mówi Xcode, że powinien zainstalować uruchomioną kopię niestandardowej klasy widoku w kreatorze interfejsów, abyś mógł ją zobaczyć na graficznym wyświetlaczu hierarchii widoków. () Niestety dla tej klasy właściwość @IBDesignable wydaje się być łuszcząca. Zadziałało, gdy po raz pierwszy go dodałem, ale potem usunąłem zawartość zwykłego tekstu w moim widoku tekstu a klikalne linki moim zdaniem zniknęły i nie udało mi się ich odzyskać.)

Kod dla mojego RTF_UITextView jest bardzo prosty. Oprócz dodania atrybutu @IBDesignable i właściwości RTF_Filename z atrybutem @IBInspectable, dodałem metodę didSet() do właściwości RTF_Filename. Metoda didSet() jest wywoływana za każdym razem, gdy zmienia się wartość właściwości RTF_Filename. Kod metody didSet() jest dość prosty:

@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.");
        }
      }

    }
  }
}

Zauważ, że jeśli właściwość @ IBDesignable nie pozwoli aby wyświetlić podgląd stylizowanego tekstu w Interface builder, może być lepiej ustawić powyższy kod jako rozszerzenie UITextView, a nie niestandardową podklasę. W ten sposób można go używać w dowolnym widoku tekstowym bez konieczności zmiany widoku tekstowego na klasę niestandardową.

Zobacz moją inną odpowiedź, jeśli musisz obsługiwać wersje iOS przed iOS 7.

Możesz pobrać przykładowy projekt, który zawiera tę nową klasę z Githuba:

DatesInSwift demo project on Github

 3
Author: Duncan C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-02 02:08:49

Wersja 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
 3
Author: ioopl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-10 14:42:02

Musiałem nadal używać czystego UILabel, tak zwanego z mojego rozpoznawania tap (jest to oparte na odpowiedzi malex tutaj: Indeks znaków w punkcie Dotykowym Dla 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];
                                          }
                                      }];
 3
Author: masty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:51

Szybki dodatek do oryginalnego opisu Duncana C vis-á-vie IB. Pisze: "to trywialne, aby hiperłącza klikalne w UITextView. Po prostu ustawiasz pole wyboru "wykrywaj linki" w widoku w IB, a ono wykrywa linki http i zamienia je w hiperłącza."

Moje doświadczenie (przynajmniej w xcode 7) jest to, że musisz również odblokować zachowanie "edytowalne", aby adresy URL zostały wykryte i klikalne.

 2
Author: sakumatto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-16 07:43:39

Jeśli chcesz użyć NSLinkAttributeName w UITextView, możesz rozważyć użycie biblioteki AttributedTextView. Jest to podklasa UITextView, która sprawia, że bardzo łatwo je obsługiwać. Więcej informacji: https://github.com/evermeer/AttributedTextView

Możesz sprawić, że dowolna część tekstu będzie oddziaływać w ten sposób (gdzie textView1 jest Iboutletem UITextView):

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) 

I do obsługi hashtagów i wzmianek możesz użyć kodu w ten sposób:

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 })
    }
 1
Author: Edwin Vermeer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-01 13:30:37

Doskonała biblioteka z @AliSoftware OHAttributedStringAdditions ułatwia dodawanie linków w UILabel Oto dokumentacja: https://github.com/AliSoftware/OHAttributedStringAdditions/wiki/link-in-UILabel

 0
Author: iGranDav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:37

Jeśli chcesz mieć aktywny podłańcuch w UITextView, możesz użyć my extended TextView... jest krótki i prosty. Możesz go edytować, jak chcesz.

Wynik: Tutaj wpisz opis obrazka

Kod: https://github.com/marekmand/ActiveSubstringTextView

 0
Author: Marek Manduch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-27 11:01:27
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;

KLUCZOWE PUNKTY:

  • Upewnij się, że UITextView w XIB jest "wybierany".
  • Upewnij się, że wyłączyłeś "edytowalne" zachowanie UITextView w XIB.
 0
Author: Shashank Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-12 06:39:30

Użyj UITextView i ustaw typy datadetectortyp Dla linku.

TAK:

testTextView.editable = false 
testTextView.dataDetectorTypes = .link

Jeśli chcesz wykryć link, numer telefonu, adres itp..then

testTextView.dataDetectorTypes = .all
 0
Author: Adarsh G J,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-27 06:51:22