En iOS 7 app, tengo un UITextView
con un enlace, pero pulsando el enlace no de fuego. Sólo responde a un torpe «toque y mantenga». Quiero responder tan pronto como un usuario pulsa sobre ella, como la forma de un UIWebView
enlace pulsa en obras. Aquí es mi configuración:
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."];
[text addAttribute:NSLinkAttributeName value:@"myurl://tapped" range:NSMakeRange(6, 16)];
self.textView.attributedText = text;
self.textView.editable = NO;
self.textView.delaysContentTouches = NO;
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
if ([[URL scheme] isEqualToString:@"myurl"])
{
//Handle tap
return NO;
}
return YES;
}
La Documentación de Apple para el shouldInteractWithURL
método de los estados: «La vista de texto llama a este método si el usuario pulsa o largo de las prensas de la URL del enlace». Al pulsar el botón está trabajando, pero el grifo no parece funcionar.
¿Alguien sabe cómo conseguir esto para responder de inmediato?
- Enlace pulsa en el reconocimiento se retrasa sigue ocurriendo en iOS9 :((((((
Es el
UITextView
seleccionables?. Tratar con:Edición:
Estoy empezando a pensar que tal vez una larga prensa es la única forma de fuego, contrario a lo que apple dice. Marque esta enlace, tal vez pueda ayudar.
[self.textView setText:nil]
antes de establecer la dirección URL.self.textView.dataDetectorTypes = UIDataDetectorTypeLink;
[self.textView.scrollEnabled:NO];
dataDetectorTypes = UIDataDetectorTypeLink
. Parece CCHLinkTextView no admite rápida pulsando los enlaces URL, lamentablemente.Si quieres ir con un nativo
UITextView
, usted puede agregar un toque de reconocimiento a su textview y obtener los atributos de la cadena en el toque ubicación. Cuando usted encuentra un enlace, se puede abrir inmediatamente.Escribí una idea que resuelve esto para iOS 7/8. Es ligera extensión de
UITextView
que también envía-[UITextViewDelegate textView:shouldInteractWithURL:inRange:]
y expone la interna toque gesto de reconocimiento.https://gist.github.com/benjaminbojko/c92ac19fe4db3302bd28
Aquí está un ejemplo rápido:El siguiente ejemplo sólo funciona en iOS 8. Ver la esencia de arriba para iOS 7 + 8.Añadir su toque de reconocimiento:
Y agregar su devolución de llamada:
Y swift versión:
Toque de reconocimiento:
De devolución de llamada:
NSLinkAttributeName
clave deattributes
produce una NSURL, por lo que el código anterior produce un error en laURLWithString
partetextStylingAtPosition:inDirection:
en iOS 7. Supongo que tenía que ver con la textPosition que tiene una longitud de 0, y por lo tanto las atribuidas cadena no tenía personajes a la realidad de host de cualquier información de enlace. Sólo un pensamiento. En última instancia, escribí esta Esencia que me funciona en iOS 7 y 8: gist.github.com/benjaminbojko/c92ac19fe4db3302bd28@objc func tappedTextView(tapGesture: UIGestureRecognizer) { let textView = tapGesture.view as! UITextView let tapLocation = tapGesture.location(in: textView) let textPosition = textView.closestPosition(to: tapLocation) let attr = textView.textStyling(at: textPosition!, in: .forward)! if let url: URL = attr[NSAttributedStringKey.link.rawValue] as? URL { UIApplication.shared.open(url, options: [:], completionHandler: nil) } }
Como nnarayann mencionado, CCHLinkTextView evita el problema de la demora del toque de reconocimiento. Esta biblioteca implementa su propio gesto de reconocimiento y ahora está disponible en la versión 1.0.
Swift 4 solución
isSelectable
estrue
ofalse
, funcionalet urlString = textView.textStyling(at: textPosition, in: .forward)?[NSAttributedStringKey.link.rawValue] as? URL, urlString == "myurl" else { return }
en Lugar de:let urlString = textView.textStyling(at: textPosition, in: .forward)?[NSAttributedStringKey.link.rawValue] as? String, urlString == "myurl" else { return }
textStyling[NSAttributedStringKey.link.rawValue]
es NSString que produce un error en la fundición a la dirección URL, puede crearURL.init(string: urlString)
si es necesarioA veces no funciona en el Simulador de iOS o sólo funciona si usted presiona & mantener.
Debe probar en un dispositivo real.
Y no se olvide de establecer
selectable
.Si no hay ninguna razón apremiante para utilizar un
UITextView
, tales como que hay otro texto que se muestra, se puede utilizar unUILabel
combinado con unUITapGestureRecognizer
para conseguir el efecto que buscas.De lo contrario, usted podría ir con un real
UIWebView
lugar.Han tratado de establecer
textview.delaysContentTouches = NO;
? Tal vez podría ayudar.touchesBegan
& es hermanos yattributesAtIndex
y comprobar laNSLinkAttribute
si es que existe.