2012-05-21 20 views
85

Deseo crear una etiqueta en la que se pueda hacer clic en mi aplicación que me lleve a una página web de Safari. También quiero que el usuario pueda llamar a los números solo haciendo clic en ellos.¿Cómo hacer URL/hacer clic en el teléfono en UILabel?

Gracias por sus consejos

+0

duplicado posible de [Crear derivación capaz de "enlaces" en la NSAttributedText de un UILabel?] (Http://stackoverflow.com/questions/1256887/create-tap-able-links-in-the-nsattributedtext-of-a-uilabel) – NAlexN

Respuesta

112

se puede utilizar un UITextView y seleccione Detección de los enlaces, números de teléfono y otras cosas en el inspector.

10

Puede hacer UIButton personalizado y setText como desee y agregar un método con eso.

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 52)]; 
    [sampleButton setTitle:@"URL Text" forState:UIControlStateNormal]; 
    [sampleButton setFont:[UIFont boldSystemFontOfSize:20]]; 

    [sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:sampleButton]; 

-(void)buttonPressed:(id)sender{ 
// open url 

} 
25

https://github.com/mattt/TTTAttributedLabel

Eso es sin duda lo que necesita. También puede aplicar atributos para su etiqueta, como el subrayado, y aplicarle diferentes colores. Solo revise las instrucciones para URLs clicables.

Principalmente, hacer algo como lo siguiente:

NSRange range = [label.text rangeOfString:@"me"]; 
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring 
+0

¡Es magnífico, gracias! Mucho mejor que usar una UITextView de varias maneras. – FreeNickname

+1

Usando Swift: 'let range = (label.text como NSString) .rangeOfString (" me ")' – nodebase

80

Uso UITextView en lugar de UILabel y tiene una propiedad para convertir el texto de hipervínculo

Objective C: 

yourTextView.editable = NO; 
yourTextView.dataDetectorTypes = UIDataDetectorTypeAll; 

Swift: 

yourTextView.editable = false; 
yourTextView.dataDetectorTypes = UIDataDetectorTypes.All; 

favor siga documentation para obtener más detalles. Esto detectará enlaces automáticamente.

Espero que esto te ayude. Gracias :)

+0

¡Gracias por esto! – Rob

+0

Siempre Bienvenido :) –

+4

esto colorea el enlace azul y lo subraya, pero parece que se puede hacer clic, al menos en iOS 7. –

7

Utilice esta me gustó mucho desde crea vínculo con el color azul al texto en particular no sólo en toda texto de la etiqueta: FRHyperLabel

Smartly applying hyperlink on Terms of Use

que hacer:

  1. Descargue desde el enlace anterior y copie FRHyperLabel.h, FRHyperLabel.m en su proyecto.

  2. gota Arrastre UILabel en su Storyboard y definir el nombre de clase personalizada a FRHyperLabel en identificar inspector como se muestra en la imagen.

enter image description here

  1. Conecte su UILabel del guión gráfico a su archivo viewController.h

@property (weak, nonatomic) IBOutlet FRHyperLabel *label;

  1. Ahora en su archivo viewController.m agregue el siguiente código.

`NSString * string = @" Al cargar estoy de acuerdo con las Condiciones de uso "; NSDictionary * attributes = @ {NSFontAttributeName: [UIFont preferredFontForTextStyle: UIFontTextStyleHeadline]};

_label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes]; 
[_label setFont:[_label.font fontWithSize:13.0]]; 

[_label setLinkForSubstring:@"Terms of Use" withLinkHandler:^(FRHyperLabel *label, NSString *substring){ 
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]]; 
}];` 
  1. y ejecutarlo.
5

Uso UITextView en lugar de UILabel y tiene una propiedad para convertir el texto de hipervínculo

Código Swift:

yourTextView.editable = false 
yourTextView.dataDetectorTypes = UIDataDetectorTypes.All 
//or 
yourTextView.dataDetectorTypes = UIDataDetectorTypes.PhoneNumber 
//or 
yourTextView.dataDetectorTypes = UIDataDetectorTypes.Link 
6

Si desea que esta sea manejado por UILabel y no UITextView, se puede hacer UILabel subclase, como éste:

class LinkedLabel: UILabel { 

fileprivate let layoutManager = NSLayoutManager() 
fileprivate let textContainer = NSTextContainer(size: CGSize.zero) 
fileprivate var textStorage: NSTextStorage? 


override init(frame aRect:CGRect){ 
    super.init(frame: aRect) 
    self.initialize() 
} 

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    self.initialize() 
} 

func initialize(){ 

    let tap = UITapGestureRecognizer(target: self, action: #selector(LinkedLabel.handleTapOnLabel)) 
    self.isUserInteractionEnabled = true 
    self.addGestureRecognizer(tap) 
} 

override var attributedText: NSAttributedString?{ 
    didSet{ 
     if let _attributedText = attributedText{ 
      self.textStorage = NSTextStorage(attributedString: _attributedText) 

      self.layoutManager.addTextContainer(self.textContainer) 
      self.textStorage?.addLayoutManager(self.layoutManager) 

      self.textContainer.lineFragmentPadding = 0.0; 
      self.textContainer.lineBreakMode = self.lineBreakMode; 
      self.textContainer.maximumNumberOfLines = self.numberOfLines; 
     } 

    } 
} 

func handleTapOnLabel(tapGesture:UITapGestureRecognizer){ 

    let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view) 
    let labelSize = tapGesture.view?.bounds.size 
    let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer) 
    let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y) 

    let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y) 
    let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) 


    self.attributedText?.enumerateAttribute(NSLinkAttributeName, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{ 
     (attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in 

     if NSLocationInRange(indexOfCharacter, range){ 
      if let _attrs = attrs{ 

       UIApplication.shared.openURL(URL(string: _attrs as! String)!) 
      } 
     } 
    }) 

}} 

esta clase fue hecha por la reutilización de código de este answer . Para realizar cadenas atribuidas, consulte este answer. Y here puede encontrar cómo hacer urls de teléfono.

+0

perfecto. ¡justo lo que estaba buscando! He estado esperando que publiques tu respuesta. –

0
extension UITapGestureRecognizer { 

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool { 

     let layoutManager = NSLayoutManager() 
     let textContainer = NSTextContainer(size: CGSize.zero) 
     let textStorage = NSTextStorage(attributedString: label.attributedText!) 

     // Configure layoutManager and textStorage 
     layoutManager.addTextContainer(textContainer) 
     textStorage.addLayoutManager(layoutManager) 

     // Configure textContainer 
     textContainer.lineFragmentPadding = 0.0 
     textContainer.lineBreakMode = label.lineBreakMode 
     textContainer.maximumNumberOfLines = label.numberOfLines 
     textContainer.size = label.bounds.size 

     // main code 
     let locationOfTouchInLabel = self.location(in: label) 

     let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInLabel, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) 
     let indexOfCharacterRange = NSRange(location: indexOfCharacter, length: 1) 
     let indexOfCharacterRect = layoutManager.boundingRect(forGlyphRange: indexOfCharacterRange, in: textContainer) 
     let deltaOffsetCharacter = indexOfCharacterRect.origin.x + indexOfCharacterRect.size.width 

     if locationOfTouchInLabel.x > deltaOffsetCharacter { 
      return false 
     } else { 
      return NSLocationInRange(indexOfCharacter, targetRange) 
     } 
    } 
} 
0

Swift 4.0 solución posible usando UIButton

 phoneButton = UIButton(frame: CGRect(x: view.frame.width * 0, y: view.frame.height * 0.1, width: view.frame.width * 1, height: view.frame.height * 0.05)) 
    phoneButton.setTitle("333-333-3333", for: .normal) 
    phoneButton.setTitleColor(UIColor(red: 0/255, green: 0/255, blue: 238/255, alpha: 1.0), for: .normal) 
    phoneButton.addTarget(self, action: #selector(self.callPhone), for: .touchUpInside) 

    @objc func callPhone(){ 

     UIApplication.shared.open(URL(string:"tel://3333333333")!, options: [:] , completionHandler: nil) 


    } 
Cuestiones relacionadas