UIWebView Bug: -[UIWebView cut:]: unrecognized selector sent to instance - ios

In the UIWebView, if an input element containing text has focus, and a button is pressed that causes the input to lose focus, then subsequently double-tapping on the input to regain focus and selecting Cut (or Copy or Paste) from the popup bar that appears causes the UIWebView to crash with the error:
-[UIWebView cut:]: unrecognized selector sent to instance 0x10900ca60
Demo project: https://github.com/guarani/WebViewDoubleTapTestTests.git
I think this must be a UIWebView bug, any ideas?
For completeness, here are the contents of my web view,
<html>
<head>
</head>
<body>
<br><br>
<input type="text">
<input type="button">
</body>
</html>
Filed a Bug Report at Apple: 15894403
Update 2019/05/30: Bug still present in iOS 12.0 (16E226)

This is an Apple bug. The problem is the cut: action is sent incorrectly in the responder chain, and ends up being sent to the UIWebView instance instead of the internal UIWebDocumentView, which implements the method.
Until Apple fixes the bug, let's have some fun with the Objective C runtime.
Here, I subclass UIWebView with the purpose of supporting all UIResponderStandardEditActions methods, by forwarding them to the correct internal instance.
#import ObjectiveC;
#interface CutCopyPasteFixedWebView : UIWebView #end
#implementation CutCopyPasteFixedWebView
- (UIView*)_internalView
{
UIView* internalView = objc_getAssociatedObject(self, "__internal_view_key");
if(internalView == nil && self.subviews.count > 0)
{
for (UIView* view in self.scrollView.subviews) {
if([view.class.description hasPrefix:#"UIWeb"])
{
internalView = view;
objc_setAssociatedObject(self, "__internal_view_key", view, OBJC_ASSOCIATION_ASSIGN);
break;
}
}
}
return internalView;
}
void webView_implement_UIResponderStandardEditActions(id self, SEL selector, id param)
{
void (*method)(id, SEL, id) = (void(*)(id, SEL, id))[[self _internalView] methodForSelector:selector];
//Call internal implementation.
method([self _internalView], selector, param);
}
- (void)_prepareForNoCrashes
{
NSArray* selectors = #[#"cut:", #"copy:", #"paste:", #"select:", #"selectAll:", #"delete:", #"makeTextWritingDirectionLeftToRight:", #"makeTextWritingDirectionRightToLeft:", #"toggleBoldface:", #"toggleItalics:", #"toggleUnderline:", #"increaseSize:", #"decreaseSize:"];
for (NSString* selName in selectors)
{
SEL selector = NSSelectorFromString(selName);
//This is safe, the method will fail if there is already an implementation.
class_addMethod(self.class, selector, (IMP)webView_implement_UIResponderStandardEditActions, "");
}
}
- (void)awakeFromNib
{
[self _prepareForNoCrashes];
[super awakeFromNib];
}
#end
Use this subclass in your storyboard.
Have fun.

If you don't mind that there is no callout for cut/paste/etc. in the case, when the UIWebview is wrongly becoming first responder, then you can also fix it with this category. This does not prohibit cut/paste/etc. when the UIWebDocumentView (correctly) becomes first responder.
#implementation UIWebView (NoWrongPerformWebview)
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
return NO;
}
#end
// Swift 4 compliant version
import UIKit
extension UIWebView {
override open func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
// Should be respond to a certain Selector ??
return responds(to: action)
}
}

If anyone is interested, here's the swift version of Leo Natans method :
import Foundation
import ObjectiveC
var AssociatedObjectHandle: UInt8 = 0
class CustomWebView: UIWebView {
func _internalView() -> UIView? {
var internalView:UIView? = objc_getAssociatedObject(self, "__internal_view_key") as? UIView
if internalView == nil && self.subviews.count > 0 {
for view: UIView in self.scrollView.subviews {
if view.self.description.hasPrefix("UIWeb") {
internalView = view
objc_setAssociatedObject(self, "__internal_view_key", view, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
}
return internalView
}
override func awakeFromNib() {
super.awakeFromNib()
self._prepareForNoCrashes()
}
func _prepareForNoCrashes() {
let selectors = ["cut:", "copy:", "paste:", "select:", "selectAll:", "delete:", "makeTextWritingDirectionLeftToRight:", "makeTextWritingDirectionRightToLeft:", "toggleBoldface:", "toggleItalics:", "toggleUnderline:", "increaseSize:", "decreaseSize:"]
for selName: String in selectors {
let selector = NSSelectorFromString(selName)
//This is safe, the method will fail if there is already an implementation.
let swizzledMethod:IMP = class_getInstanceMethod(CustomWebView.self, #selector(CustomWebView.webView_implement_UIResponderStandardEditActions))
class_addMethod(CustomWebView.self, selector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
}
}
func webView_implement_UIResponderStandardEditActions(this:AnyObject, selector:Selector, param:AnyObject)
{
let method = {(val1: UIView?, val2: Selector, val3: AnyObject) -> Void in
self._internalView()?.methodForSelector(selector)
}
method(self._internalView(), selector, param);
}
}

- (UIView *)_internalView {
UIView *internalView = nil;
if (internalView == nil && self.subviews.count > 0) {
for (UIView *view in self.scrollView.subviews) {
if([view.class.description hasPrefix:#"UIWeb"]) {
internalView = view;
break;
}
}
}
return internalView;
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
struct objc_method_description methodDescription = protocol_getMethodDescription(#protocol(UIResponderStandardEditActions), aSelector, NO, YES);
if (methodDescription.name == aSelector) {
UIView *view = [self _internalView];
if ([view respondsToSelector:aSelector]) {
return view;
}
}
return [super forwardingTargetForSelector:aSelector];
}

Related

Method swizzling not woking in Cocoa pod

I'm developing a pod which should use method swizzling at some point and I have a problem to call swizzled method when calling original one.
I checked my swizzling in the simple POC (to be sure my swizzling is ok) and it works perfectly fine, but as cocoa pod (with mark use_framework in pod file even) it doesn't work, so I was debugging it and method exchange happens, it finds original method and swizzled method implementations, etc. but swizzled method doesn't get called which should happen in the main app, that has my pod.
method swizzling is written using objective-c
Anyone had such problems?
Code from my POC
Swizzler
- (BOOL)swizzleClass:(Class)class
replaceInstanceMethod:(SEL)methodSelector1
withMethod:(SEL)methodSelector2 {
if (!class || !methodSelector1 || !methodSelector2) {
NSLog(#"Nil Parameter(s) found when swizzling.");
return NO;
}
Method method1 = class_getInstanceMethod(class, methodSelector1);
Method method2 = class_getInstanceMethod(class, methodSelector2);
if (method1 && method2) {
method_exchangeImplementations(method1, method2);
return YES;
} else {
NSLog(#"Swizzling Method(s) not found while swizzling class %#.", NSStringFromClass(class));
return NO;
}
}
Class category
+ (void)load {
static dispatch_once_t once_token;
dispatch_once(&once_token, ^{
swizzler = [[Swizzler alloc] init];
swizzleSuccess = [swizzler swizzleClass:self replaceInstanceMethod:#selector(wristLocation) withMethod: #selector(swizzled_wristLocation)];
if (swizzleSuccess) {
NSLog(#"Successss 🦭 swizzle");
} else {
NSLog(#"Cannot swizzle");
}
});
}
- (void)setLocation:(WKInterfaceDeviceWristLocation)location {
testWristLocation = [[NSNumber alloc] initWithInt: location];
}
- (WKInterfaceDeviceWristLocation)swizzled_wristLocation {
NSLog(#"Called swizzled method 🐳.");
[self swizzled_wristLocation];
return [testWristLocation intValue];
}
Class where I call it
#IBOutlet weak var locationLabel: WKInterfaceLabel!
override func awake(withContext context: Any?) {
WKInterfaceDevice.current().setLocation(WKInterfaceDeviceWristLocation.right)
updateLocation()
}
#IBAction func checkLocation() {
updateLocation()
}
dynamic private func updateLocation() {
let location = WKInterfaceDevice.current().wristLocation
switch location {
case .left:
self.locationLabel.setText("left")
case .right:
self.locationLabel.setText("right")
#unknown default:
self.locationLabel.setText("unknown")
}
}
So, I find out what was wrong here.
The problem was in wrong target membership, I was swizzling in one target and expecting swizzled method to be called in another (which is basically another app). Right code sharing fixed the problem.

How can I hide the input accessory view of the keyboard when using a WKWebView?

We have a webview in our app to edit some text in a semi-wysiwyg style. It's just a fullscreen text area so we don't want those next/previous/done buttons on the keyboard taking in precious screen space. Previously, the following worked to remove the whole bar where those buttons are shown:
-(void)__removeInputAccessoryView {
UIView* subview;
for (UIView* view in _editorView.scrollView.subviews) {
if([[view.class description] hasPrefix:#"UIWeb"])
subview = view;
}
if(subview == nil) {
return;
}
NSString* name = [NSString stringWithFormat:#"%#RWWebviewHelper", subview.class.superclass];
Class newClass = NSClassFromString(name);
if(newClass == nil) {
newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
if(!newClass) {
return;
}
Method method = class_getInstanceMethod([RWWebviewHelper class], #selector(inputAccessoryView));
class_addMethod(newClass, #selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
objc_registerClassPair(newClass);
}
object_setClass(subview, newClass);
}
I found similar snippets on SO and Github, both in Objective-C and Swift. I'm currently converting this class from Objective-C to Swift and from using UIWebView to using a WKWebView. I found this on SO somewhere:
private func removeInputAccessoryView() {
final class FauxBarHelper: NSObject {
var inputAccessoryView: AnyObject? { return nil }
}
editorView.scrollView.subviews.forEach { view in
if String(describing: type(of: view)).hasPrefix("WKcon") {
let noInputAccessoryViewClassName = "\(view.superclass!)_NoInputAccessoryView"
var newClass: AnyClass? = NSClassFromString(noInputAccessoryViewClassName)
if newClass == nil {
let targetClass: AnyClass = object_getClass(view)
newClass = objc_allocateClassPair(targetClass, noInputAccessoryViewClassName.cString(using: String.Encoding.ascii)!, 0)
}
let originalMethod = class_getInstanceMethod(FauxBarHelper.self, #selector(getter: FauxBarHelper.inputAccessoryView))
class_addMethod(newClass!.self, #selector(getter: FauxBarHelper.inputAccessoryView), method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
object_setClass(view, newClass)
}
}
}
But it doesn't hide the bar. I'm not too well versed in hacking the private API and after playing around with the values in that snippet I can't find a way to hide the bar. I know this is a store rejection risk, but you know how clients are. I need to get this working. I can work with an Objective-C snippet, but prefer Swift.
Does anyone have an idea? I feel it shouldn't be very hard to hide a button bar from an onscreen keyboard, am I missing something simple?

iOS 7 UIWebView keyboard issue

I have to remove this bar as here link but for iOS 7 this code does not work.
We remove this bar with some Objective C runtime trickery.
We have a class which has one method:
#interface _SwizzleHelper : NSObject #end
#implementation _SwizzleHelper
-(id)inputAccessoryView
{
return nil;
}
#end
Once we have a web view which we want to remove the bar from, we iterate its scroll view's subviews and take the UIWebDocumentView class. We then dynamically make the superclass of the class we created above to be the subview's class (UIWebDocumentView - but we cannot say that upfront because this is private API), and replace the subview's class to our class.
#import "objc/runtime.h"
-(void)__removeInputAccessoryView
{
UIView* subview;
for (UIView* view in self.scrollView.subviews) {
if([[view.class description] hasPrefix:#"UIWeb"])
subview = view;
}
if(subview == nil) return;
NSString* name = [NSString stringWithFormat:#"%#_SwizzleHelper", subview.class.superclass];
Class newClass = NSClassFromString(name);
if(newClass == nil)
{
newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
if(!newClass) return;
Method method = class_getInstanceMethod([_SwizzleHelper class], #selector(inputAccessoryView));
class_addMethod(newClass, #selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
objc_registerClassPair(newClass);
}
object_setClass(subview, newClass);
}
The equivalent of the above in Swift 3.0:
import UIKit
import ObjectiveC
var swizzledClassMapping = [AnyClass]()
extension UIWebView {
func noInputAccessoryView() -> UIView? {
return nil
}
public func removeInputAccessoryView() {
var subview: AnyObject?
for (_, view) in scrollView.subviews.enumerated() {
if NSStringFromClass(type(of: view)).hasPrefix("UIWeb") {
subview = view
}
}
guard subview != nil else {
return
}
//Guard in case this method is called twice on the same webview.
guard !(swizzledClassMapping as NSArray).contains(type(of: subview!)) else {
return;
}
let className = "\type(of: subview!)_SwizzleHelper"
var newClass : AnyClass? = NSClassFromString(className)
if newClass == nil {
newClass = objc_allocateClassPair(type(of: subview!), className, 0)
guard newClass != nil else {
return;
}
let method = class_getInstanceMethod(type(of: self), #selector(UIWebView.noInputAccessoryView))
class_addMethod(newClass!, #selector(getter: UIResponder.inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method))
objc_registerClassPair(newClass!)
swizzledClassMapping += [newClass!]
}
object_setClass(subview!, newClass!)
}
}
I've made a cocoapod based on this blog post from #bjhomer.
You can replace the inputaccessoryview and not just hide it. I hope this will help people with the same issue.
https://github.com/lauracpierre/FA_InputAccessoryViewWebView
You can find the cocoapod page right here.
I've came across this awesome solution, but I needed to get the inputAccessoryView back as well. I added this method:
- (void)__addInputAccessoryView {
UIView* subview;
for (UIView* view in self.scrollView.subviews) {
if([[view.class description] hasSuffix:#"SwizzleHelper"])
subview = view;
}
if(subview == nil) return;
Class newClass = subview.superclass;
object_setClass(subview, newClass);
}
It does seem to work as intended with no side effects, but I can't get rid of the feeling that my pants are on fire.
If you want Leo Natan's solution to work with WKWebView instead of UIWebView just change prefix from "UIWeb" to "WKContent".
I created a gist to accomplish this:
https://gist.github.com/kgaidis/5f9a8c7063b687cc3946fad6379c1a66
It's a UIWebView category where all you do is change the customInputAccessoryView property:
#interface UIWebView (CustomInputAccessoryView)
#property (strong, nonatomic) UIView *customInputAccessoryView;
#end
You can either set it to nil to remove it or you can set a new view on it to change it.
Keep in mind, this also uses private API's, so use at your own risk, but it seems like a lot of apps do similar things nonetheless.

Intercept Objective-C delegate messages within a subclass

I have a subclass of UIScrollView in which I need to internally respond to scrolling behaviour. However, the viewcontroller will still need to listen to scrolling delegate callbacks, so I can't outright steal the delegate within my component.
Is there a way to keep the property named "delegate" and just listen to messages sent along it, or else somehow internally hijack the delegate property and forward messages outward after running some code?
To avoid overriding all of the delegate methods manually, you can use message forwarding. I just implemented the same thing using an intermediate proxy class as follows:
MessageInterceptor.h
#interface MessageInterceptor : NSObject {
id receiver;
id middleMan;
}
#property (nonatomic, assign) id receiver;
#property (nonatomic, assign) id middleMan;
#end
MessageInterceptor.m
#implementation MessageInterceptor
#synthesize receiver;
#synthesize middleMan;
- (id)forwardingTargetForSelector:(SEL)aSelector {
if ([middleMan respondsToSelector:aSelector]) { return middleMan; }
if ([receiver respondsToSelector:aSelector]) { return receiver; }
return [super forwardingTargetForSelector:aSelector];
}
- (BOOL)respondsToSelector:(SEL)aSelector {
if ([middleMan respondsToSelector:aSelector]) { return YES; }
if ([receiver respondsToSelector:aSelector]) { return YES; }
return [super respondsToSelector:aSelector];
}
#end
MyScrollView.h
#import "MessageInterceptor.h"
#interface MyScrollView : UIScrollView {
MessageInterceptor * delegate_interceptor;
//...
}
//...
#end
MyScrollView.m (Edited, with thanks to jhabbott):
#implementation MyScrollView
- (id)delegate { return delegate_interceptor.receiver; }
- (void)setDelegate:(id)newDelegate {
[super setDelegate:nil];
[delegate_interceptor setReceiver:newDelegate];
[super setDelegate:(id)delegate_interceptor];
}
- (id)init* {
//...
delegate_interceptor = [[MessageInterceptor alloc] init];
[delegate_interceptor setMiddleMan:self];
[super setDelegate:(id)delegate_interceptor];
//...
}
- (void)dealloc {
//...
[delegate_interceptor release];
//...
}
// delegate method override:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// 1. your custom code goes here
// 2. forward to the delegate as usual
if ([self.delegate respondsToSelector:#selector(scrollViewDidScroll:)]) {
[self.delegate scrollViewDidScroll:scrollView];
}
}
#end
With this approach, the MessageInterceptor object will automatically forward all delegate messages to the regular delegate object, except for the ones that you override in your custom subclass.
The post from e.James gave an excellent solution for most views. But for keyboard dependent views like UITextField and UITextView, it often results in a situation of infinite loop. To get rid of it, I fixed it with some additional code what checks whether the selector is contained in specific protocol(s) or not.
WZProtocolInterceptor.h
#import <Foundation/Foundation.h>
#interface WZProtocolInterceptor : NSObject
#property (nonatomic, readonly, copy) NSArray * interceptedProtocols;
#property (nonatomic, weak) id receiver;
#property (nonatomic, weak) id middleMan;
- (instancetype)initWithInterceptedProtocol:(Protocol *)interceptedProtocol;
- (instancetype)initWithInterceptedProtocols:(Protocol *)firstInterceptedProtocol, ... NS_REQUIRES_NIL_TERMINATION;
- (instancetype)initWithArrayOfInterceptedProtocols:(NSArray *)arrayOfInterceptedProtocols;
#end
WZProtocolInterceptor.m
#import <objc/runtime.h>
#import "WZProtocolInterceptor.h"
static inline BOOL selector_belongsToProtocol(SEL selector, Protocol * protocol);
#implementation WZProtocolInterceptor
- (id)forwardingTargetForSelector:(SEL)aSelector
{
if ([self.middleMan respondsToSelector:aSelector] &&
[self isSelectorContainedInInterceptedProtocols:aSelector])
return self.middleMan;
if ([self.receiver respondsToSelector:aSelector])
return self.receiver;
return [super forwardingTargetForSelector:aSelector];
}
- (BOOL)respondsToSelector:(SEL)aSelector
{
if ([self.middleMan respondsToSelector:aSelector] &&
[self isSelectorContainedInInterceptedProtocols:aSelector])
return YES;
if ([self.receiver respondsToSelector:aSelector])
return YES;
return [super respondsToSelector:aSelector];
}
- (instancetype)initWithInterceptedProtocol:(Protocol *)interceptedProtocol
{
self = [super init];
if (self) {
_interceptedProtocols = #[interceptedProtocol];
}
return self;
}
- (instancetype)initWithInterceptedProtocols:(Protocol *)firstInterceptedProtocol, ...;
{
self = [super init];
if (self) {
NSMutableArray * mutableProtocols = [NSMutableArray array];
Protocol * eachInterceptedProtocol;
va_list argumentList;
if (firstInterceptedProtocol)
{
[mutableProtocols addObject:firstInterceptedProtocol];
va_start(argumentList, firstInterceptedProtocol);
while ((eachInterceptedProtocol = va_arg(argumentList, id))) {
[mutableProtocols addObject:eachInterceptedProtocol];
}
va_end(argumentList);
}
_interceptedProtocols = [mutableProtocols copy];
}
return self;
}
- (instancetype)initWithArrayOfInterceptedProtocols:(NSArray *)arrayOfInterceptedProtocols
{
self = [super init];
if (self) {
_interceptedProtocols = [arrayOfInterceptedProtocols copy];
}
return self;
}
- (void)dealloc
{
_interceptedProtocols = nil;
}
- (BOOL)isSelectorContainedInInterceptedProtocols:(SEL)aSelector
{
__block BOOL isSelectorContainedInInterceptedProtocols = NO;
[self.interceptedProtocols enumerateObjectsUsingBlock:^(Protocol * protocol, NSUInteger idx, BOOL *stop) {
isSelectorContainedInInterceptedProtocols = selector_belongsToProtocol(aSelector, protocol);
* stop = isSelectorContainedInInterceptedProtocols;
}];
return isSelectorContainedInInterceptedProtocols;
}
#end
BOOL selector_belongsToProtocol(SEL selector, Protocol * protocol)
{
// Reference: https://gist.github.com/numist/3838169
for (int optionbits = 0; optionbits < (1 << 2); optionbits++) {
BOOL required = optionbits & 1;
BOOL instance = !(optionbits & (1 << 1));
struct objc_method_description hasMethod = protocol_getMethodDescription(protocol, selector, required, instance);
if (hasMethod.name || hasMethod.types) {
return YES;
}
}
return NO;
}
And here is the Swift 2 version:
//
// NSProtocolInterpreter.swift
// Nest
//
// Created by Manfred Lau on 11/28/14.
// Copyright (c) 2014 WeZZard. All rights reserved.
//
import Foundation
/**
`NSProtocolInterceptor` is a proxy which intercepts messages to the middle man
which originally intended to send to the receiver.
- Discussion: `NSProtocolInterceptor` is a class cluster which dynamically
subclasses itself to conform to the intercepted protocols at the runtime.
*/
public final class NSProtocolInterceptor: NSObject {
/// Returns the intercepted protocols
public var interceptedProtocols: [Protocol] { return _interceptedProtocols }
private var _interceptedProtocols: [Protocol] = []
/// The receiver receives messages
public weak var receiver: NSObjectProtocol?
/// The middle man intercepts messages
public weak var middleMan: NSObjectProtocol?
private func doesSelectorBelongToAnyInterceptedProtocol(
aSelector: Selector) -> Bool
{
for aProtocol in _interceptedProtocols
where sel_belongsToProtocol(aSelector, aProtocol)
{
return true
}
return false
}
/// Returns the object to which unrecognized messages should first be
/// directed.
public override func forwardingTargetForSelector(aSelector: Selector)
-> AnyObject?
{
if middleMan?.respondsToSelector(aSelector) == true &&
doesSelectorBelongToAnyInterceptedProtocol(aSelector)
{
return middleMan
}
if receiver?.respondsToSelector(aSelector) == true {
return receiver
}
return super.forwardingTargetForSelector(aSelector)
}
/// Returns a Boolean value that indicates whether the receiver implements
/// or inherits a method that can respond to a specified message.
public override func respondsToSelector(aSelector: Selector) -> Bool {
if middleMan?.respondsToSelector(aSelector) == true &&
doesSelectorBelongToAnyInterceptedProtocol(aSelector)
{
return true
}
if receiver?.respondsToSelector(aSelector) == true {
return true
}
return super.respondsToSelector(aSelector)
}
/**
Create a protocol interceptor which intercepts a single Objecitve-C
protocol.
- Parameter protocols: An Objective-C protocol, such as
UITableViewDelegate.self.
*/
public class func forProtocol(aProtocol: Protocol)
-> NSProtocolInterceptor
{
return forProtocols([aProtocol])
}
/**
Create a protocol interceptor which intercepts a variable-length sort of
Objecitve-C protocols.
- Parameter protocols: A variable length sort of Objective-C protocol,
such as UITableViewDelegate.self.
*/
public class func forProtocols(protocols: Protocol ...)
-> NSProtocolInterceptor
{
return forProtocols(protocols)
}
/**
Create a protocol interceptor which intercepts an array of Objecitve-C
protocols.
- Parameter protocols: An array of Objective-C protocols, such as
[UITableViewDelegate.self].
*/
public class func forProtocols(protocols: [Protocol])
-> NSProtocolInterceptor
{
let protocolNames = protocols.map { NSStringFromProtocol($0) }
let sortedProtocolNames = protocolNames.sort()
let concatenatedName = sortedProtocolNames.joinWithSeparator(",")
let theConcreteClass = concreteClassWithProtocols(protocols,
concatenatedName: concatenatedName,
salt: nil)
let protocolInterceptor = theConcreteClass.init()
as! NSProtocolInterceptor
protocolInterceptor._interceptedProtocols = protocols
return protocolInterceptor
}
/**
Return a subclass of `NSProtocolInterceptor` which conforms to specified
protocols.
- Parameter protocols: An array of Objective-C protocols. The
subclass returned from this function will conform to these protocols.
- Parameter concatenatedName: A string which came from concatenating
names of `protocols`.
- Parameter salt: A UInt number appended to the class name
which used for distinguishing the class name itself from the duplicated.
- Discussion: The return value type of this function can only be
`NSObject.Type`, because if you return with `NSProtocolInterceptor.Type`,
you can only init the returned class to be a `NSProtocolInterceptor` but not
its subclass.
*/
private class func concreteClassWithProtocols(protocols: [Protocol],
concatenatedName: String,
salt: UInt?)
-> NSObject.Type
{
let className: String = {
let basicClassName = "_" +
NSStringFromClass(NSProtocolInterceptor.self) +
"_" + concatenatedName
if let salt = salt { return basicClassName + "_\(salt)" }
else { return basicClassName }
}()
let nextSalt = salt.map {$0 + 1}
if let theClass = NSClassFromString(className) {
switch theClass {
case let anInterceptorClass as NSProtocolInterceptor.Type:
let isClassConformsToAllProtocols: Bool = {
// Check if the found class conforms to the protocols
for eachProtocol in protocols
where !class_conformsToProtocol(anInterceptorClass,
eachProtocol)
{
return false
}
return true
}()
if isClassConformsToAllProtocols {
return anInterceptorClass
} else {
return concreteClassWithProtocols(protocols,
concatenatedName: concatenatedName,
salt: nextSalt)
}
default:
return concreteClassWithProtocols(protocols,
concatenatedName: concatenatedName,
salt: nextSalt)
}
} else {
let subclass = objc_allocateClassPair(NSProtocolInterceptor.self,
className,
0)
as! NSObject.Type
for eachProtocol in protocols {
class_addProtocol(subclass, eachProtocol)
}
objc_registerClassPair(subclass)
return subclass
}
}
}
/**
Returns true when the given selector belongs to the given protocol.
*/
public func sel_belongsToProtocol(aSelector: Selector,
_ aProtocol: Protocol) -> Bool
{
for optionBits: UInt in 0..<(1 << 2) {
let isRequired = optionBits & 1 != 0
let isInstance = !(optionBits & (1 << 1) != 0)
let methodDescription = protocol_getMethodDescription(aProtocol,
aSelector, isRequired, isInstance)
if !objc_method_description_isEmpty(methodDescription)
{
return true
}
}
return false
}
public func objc_method_description_isEmpty(
var methodDescription: objc_method_description)
-> Bool
{
let ptr = withUnsafePointer(&methodDescription) { UnsafePointer<Int8>($0) }
for offset in 0..<sizeof(objc_method_description) {
if ptr[offset] != 0 {
return false
}
}
return true
}
Actually, this worked for me:
#implementation MySubclass {
id _actualDelegate;
}
// There is no need to set the value of _actualDelegate in an init* method
- (void)setDelegate:(id)newDelegate {
[super setDelegate:nil];
_actualDelegate = newDelegate;
[super setDelegate:(id)self];
}
- (id)delegate {
return self;
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
if ([_actualDelegate respondsToSelector:aSelector]) { return _actualDelegate; }
return [super forwardingTargetForSelector:aSelector];
}
- (BOOL)respondsToSelector:(SEL)aSelector {
return [super respondsToSelector:aSelector] || [_actualDelegate respondsToSelector:aSelector];
}
#end
...making the subclass to be the message interceptor in the awesome answer given by e.James.
Yes, but you'll have to override every delegate method in the docs. Basically, make a second delegate property and implement the delegate protocol. When your delegate methods are called, take care of your business and then call the same method on your second delegate from the delegate method that was just run. E.g.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Do stuff here
if ([self.delegate2 respondsToSelector:#selector(scrollViewDidScroll:)]) {
[self.delegate2 scrollViewDidScroll:scrollView];
}
}

How to navigate through textfields (Next / Done Buttons)

How can I navigate through all my text fields with the "Next" Button on the iPhone Keyboard?
The last text field should close the Keyboard.
I've setup the IB the Buttons (Next / Done) but now I'm stuck.
I implemented the textFieldShouldReturn action but now the Next and Done Buttons close the Keyboard.
In Cocoa for Mac OS X, you have the next responder chain, where you can ask the text field what control should have focus next. This is what makes tabbing between text fields work. But since iOS devices do not have a keyboard, only touch, this concept has not survived the transition to Cocoa Touch.
This can be easily done anyway, with two assumptions:
All "tabbable" UITextFields are on the same parent view.
Their "tab-order" is defined by the tag property.
Assuming this you can override textFieldShouldReturn: as this:
-(BOOL)textFieldShouldReturn:(UITextField*)textField
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
Add some more code, and the assumptions can be ignored as well.
Swift 4.0
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
// Try to find next responder
let nextResponder = textField.superview?.viewWithTag(nextTag) as UIResponder!
if nextResponder != nil {
// Found next responder, so set it
nextResponder?.becomeFirstResponder()
} else {
// Not found, so remove keyboard
textField.resignFirstResponder()
}
return false
}
If the superview of the text field will be a UITableViewCell then next responder will be
let nextResponder = textField.superview?.superview?.superview?.viewWithTag(nextTag) as UIResponder!
There is a much more elegant solution which blew me away the first time I saw it. Benefits:
Closer to OSX textfield implementation where a textfield knows where the focus should go next
Does not rely on setting or using tags -- which are, IMO fragile for this use case
Can be extended to work with both UITextField and UITextView controls -- or any keyboard entry UI control
Doesn't clutter your view controller with boilerplate UITextField delegate code
Integrates nicely with IB and can be configured through the familiar option-drag-drop to connect outlets.
Create a UITextField subclass which has an IBOutlet property called nextField. Here's the header:
#interface SOTextField : UITextField
#property (weak, nonatomic) IBOutlet UITextField *nextField;
#end
And here's the implementation:
#implementation SOTextField
#end
In your view controller, you'll create the -textFieldShouldReturn: delegate method:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ([textField isKindOfClass:[SOTextField class]]) {
UITextField *nextField = [(SOTextField *)textField nextField];
if (nextField) {
dispatch_async(dispatch_get_current_queue(), ^{
[nextField becomeFirstResponder];
});
}
else {
[textField resignFirstResponder];
}
}
return YES;
}
In IB, change your UITextFields to use the SOTextField class. Next, also in IB, set the delegate for each of the 'SOTextFields'to 'File's Owner' (which is right where you put the code for the delegate method - textFieldShouldReturn). The beauty of this design is that now you can simply right-click on any textField and assign the nextField outlet to the next SOTextField object you want to be the next responder.
Moreover, you can do cool things like loop the textFields so that after the last one loses focus, the first one will receive focus again.
This can easily be extended to automatically assign the returnKeyType of the SOTextField to a UIReturnKeyNext if there is a nextField assigned -- one less thing manually configure.
Here's one without delegation:
tf1.addTarget(tf2, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)
tf2.addTarget(tf3, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)
ObjC:
[tf1 addTarget:tf2 action:#selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];
[tf2 addTarget:tf3 action:#selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];
Works using the (mostly unknown) UIControlEventEditingDidEndOnExit UITextField action.
You can also easily hook this up in the storyboard, so no delegation or code is required.
Edit: actually I cannot figure out how to hook this up in storyboard. becomeFirstResponder does not seem to be a offered action for this control-event, which is a pity. Still, you can hook all your textfields up to a single action in your ViewController which then determines which textField to becomeFirstResponder based on the sender (though then it is not as elegant as the above programmatic solution so IMO do it with the above code in viewDidLoad).
Here is my solution for this problem.
To solve this (and because I hate relying on tags to do stuff) I decided to add a custom property to the UITextField object. In other words I created a category on UITextField like this :
UITextField+Extended.h
#interface UITextField (Extended)
#property(retain, nonatomic)UITextField* nextTextField;
#end
UITextField+Extended.m
#import "UITextField+Extended.h"
#import <objc/runtime.h>
static char defaultHashKey;
#implementation UITextField (Extended)
- (UITextField*) nextTextField {
return objc_getAssociatedObject(self, &defaultHashKey);
}
- (void) setNextTextField:(UITextField *)nextTextField{
objc_setAssociatedObject(self, &defaultHashKey, nextTextField, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#end
Now, here is how I use it :
UITextField *textField1 = ...init your textfield
UITextField *textField2 = ...init your textfield
UITextField *textField3 = ...init your textfield
textField1.nextTextField = textField2;
textField2.nextTextField = textField3;
textField3.nextTextField = nil;
And implement the textFieldShouldReturn method :
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
UITextField *next = theTextField.nextTextField;
if (next) {
[next becomeFirstResponder];
} else {
[theTextField resignFirstResponder];
}
return NO;
}
I now have kind of a linked list of UITextField, each one knowing who's next in the line.
Hope it'll help.
A swift extension that applies mxcl's answer to make this particularly easy (adapted to swift 2.3 by Traveler):
extension UITextField {
class func connectFields(fields:[UITextField]) -> Void {
guard let last = fields.last else {
return
}
for i in 0 ..< fields.count - 1 {
fields[i].returnKeyType = .Next
fields[i].addTarget(fields[i+1], action: "becomeFirstResponder", forControlEvents: .EditingDidEndOnExit)
}
last.returnKeyType = .Done
last.addTarget(last, action: #selector(UIResponder.resignFirstResponder), forControlEvents: .EditingDidEndOnExit)
}
}
It's easy to use:
UITextField.connectFields([field1, field2, field3])
The extension will set the return button to "Next" for all but the last field and to "Done" for the last field, and shift focus / dismiss the keyboard when these are tapped.
Swift < 2.3
extension UITextField {
class func connectFields(fields:[UITextField]) -> Void {
guard let last = fields.last else {
return
}
for var i = 0; i < fields.count - 1; i += 1 {
fields[i].returnKeyType = .Next
fields[i].addTarget(fields[i+1], action: "becomeFirstResponder", forControlEvents: .EditingDidEndOnExit)
}
last.returnKeyType = .Done
last.addTarget(last, action: "resignFirstResponder", forControlEvents: .EditingDidEndOnExit)
}
}
SWIFT 3:
use like this -
UITextField.connectFields(fields: [field1, field2])
Extension:
extension UITextField {
class func connectFields(fields:[UITextField]) -> Void {
guard let last = fields.last else {
return
}
for i in 0 ..< fields.count - 1 {
fields[i].returnKeyType = .next
fields[i].addTarget(fields[i+1], action: #selector(UIResponder.becomeFirstResponder), for: .editingDidEndOnExit)
}
last.returnKeyType = .go
last.addTarget(last, action: #selector(UIResponder.resignFirstResponder), for: .editingDidEndOnExit)
}
}
A more consistent and robust way is to use NextResponderTextField
You can configure it totally from interface builder with no need for setting the delegate or using view.tag.
All you need to do is
Set the class type of your UITextField to be NextResponderTextField
Then set the outlet of the nextResponderField to point to the next responder it can be anything UITextField or any UIResponder subclass. It can be also a UIButton and the library is smart enough to trigger the TouchUpInside event of the button only if it's enabled.
Here is the library in action:
I like the OO solutions that have already been suggested by Anth0 and Answerbot. However, I was working on a quick and small POC, so I didn't want to clutter things with subclasses and categories.
Another simple solution is to create an NSArray of fields and lookup the next field when you press next. Not an OO solution, but quick, simple, and easy to implement. Also, you can see and modify the ordering at a glance.
Here's my code (built upon other answers in this thread):
#property (nonatomic) NSArray *fieldArray;
- (void)viewDidLoad {
[super viewDidLoad];
fieldArray = [NSArray arrayWithObjects: firstField, secondField, thirdField, nil];
}
- (BOOL) textFieldShouldReturn:(UITextField *) textField {
BOOL didResign = [textField resignFirstResponder];
if (!didResign) return NO;
NSUInteger index = [self.fieldArray indexOfObject:textField];
if (index == NSNotFound || index + 1 == fieldArray.count) return NO;
id nextField = [fieldArray objectAtIndex:index + 1];
activeField = nextField;
[nextField becomeFirstResponder];
return NO;
}
I always return NO because I don't want a line break inserted. Just thought I'd point that out since when I returned YES it would automatically exit the subsequent fields or insert a line break in my TextView. It took me a bit of time to figure that out.
activeField keeps track of the active field in case scrolling is necessary to unobscure the field from the keyboard. If you have similar code, make sure you assign the activeField before changing the first responder. Changing first responder is immediate and will fire the KeyboardWasShown event immediately.
Here is an implementation of tabbing using a category on UIControl. This solution has all of the advantages of the methods from Michael and Anth0, but works for all UIControls, not just UITextFields. It also works seamlessly with Interface Builder and storyboards.
Source and sample app: GitHub repository for UIControlsWithTabbing
Usage:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField transferFirstResponderToNextControl];
return NO;
}
Header:
//
// UIControl+NextControl.h
// UIControlsWithTabbing
//
#import <UIKit/UIKit.h>
#interface UIControl (NextControl)
#property (nonatomic, weak) IBOutlet UIControl *nextControl;
- (BOOL)transferFirstResponderToNextControl;
#end
Implementation:
#import "UIControl+NextControl.h"
#import <objc/runtime.h>
static char defaultHashKey;
#implementation UIControl (NextControl)
- (UIControl *)nextControl
{
return objc_getAssociatedObject(self, &defaultHashKey);
}
- (void)setNextControl:(UIControl *)nextControl
{
objc_setAssociatedObject(self, &defaultHashKey, nextControl, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)transferFirstResponderToNextControl
{
if (self.nextControl)
{
[self.nextControl becomeFirstResponder];
return YES;
}
[self resignFirstResponder];
return NO;
}
#end
I have tried many codes and finally, this worked for me in Swift 3.0 Latest [March 2017]
The ViewController class should be inherited the UITextFieldDelegate for making this code working.
class ViewController: UIViewController,UITextFieldDelegate
Add the Text field with the Proper Tag number and this tag number is used to take the control to appropriate text field based on incremental tag number assigned to it.
override func viewDidLoad() {
userNameTextField.delegate = self
userNameTextField.tag = 0
userNameTextField.returnKeyType = UIReturnKeyType.next
passwordTextField.delegate = self
passwordTextField.tag = 1
passwordTextField.returnKeyType = UIReturnKeyType.go
}
In the above code, the returnKeyType = UIReturnKeyType.next where will make the Key pad return key to display as Next you also have other options as Join/Go etc, based on your application change the values.
This textFieldShouldReturn is a method of UITextFieldDelegate controlled and here we have next field selection based on the Tag value incrementation
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
return true;
}
return false
}
After you exit from one text field, you call [otherTextField becomeFirstResponder] and the next field gets focus.
This can actually be a tricky problem to deal with since often you'll also want to scroll the screen or otherwise adjust the position of the text field so it's easy to see when editing. Just make sure to do a lot of testing with coming into and out of the text fields in different ways and also leaving early (always give the user an option to dismiss the keyboard instead of going to the next field, usually with "Done" in the nav bar)
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[[self.view viewWithTag:textField.tag+1] becomeFirstResponder];
return YES;
}
I am surprised by how many answers here fail to understand one simple concept: navigating through controls in your app is not something the views themselves should do. It's the controller's job to decide which control to make the next first responder.
Also most answers only applied to navigating forward, but users may also want to go backwards.
So here's what I've come up with. Your form should be managed by a view controller, and view controllers are part of the responder chain. So you're perfectly free to implement the following methods:
#pragma mark - Key Commands
- (NSArray *)keyCommands
{
static NSArray *commands;
static dispatch_once_t once;
dispatch_once(&once, ^{
UIKeyCommand *const forward = [UIKeyCommand keyCommandWithInput:#"\t" modifierFlags:0 action:#selector(tabForward:)];
UIKeyCommand *const backward = [UIKeyCommand keyCommandWithInput:#"\t" modifierFlags:UIKeyModifierShift action:#selector(tabBackward:)];
commands = #[forward, backward];
});
return commands;
}
- (void)tabForward:(UIKeyCommand *)command
{
NSArray *const controls = self.controls;
UIResponder *firstResponder = nil;
for (UIResponder *const responder in controls) {
if (firstResponder != nil && responder.canBecomeFirstResponder) {
[responder becomeFirstResponder]; return;
}
else if (responder.isFirstResponder) {
firstResponder = responder;
}
}
[controls.firstObject becomeFirstResponder];
}
- (void)tabBackward:(UIKeyCommand *)command
{
NSArray *const controls = self.controls;
UIResponder *firstResponder = nil;
for (UIResponder *const responder in controls.reverseObjectEnumerator) {
if (firstResponder != nil && responder.canBecomeFirstResponder) {
[responder becomeFirstResponder]; return;
}
else if (responder.isFirstResponder) {
firstResponder = responder;
}
}
[controls.lastObject becomeFirstResponder];
}
Additional logic for scrolling offscreen responders visible beforehand may apply.
Another advantage of this approach is that you don't need to subclass all kinds of controls you may want to display (like UITextFields) but can instead manage the logic at controller level, where, let's be honest, is the right place to do so.
A very easy method for dismissing the keyboard when the 'Done' button is pressed is:
Create a new IBAction in the header
- (IBAction)textFieldDoneEditing:(id)sender;
In the implementation file (.m file) add the following method:
- (IBAction)textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
Then, when you come to link the IBAction to the textfield - link to the 'Did End On Exit' event.
First set keyboard return key in xib, otherwise you can write code in viewdidload:
passWord.returnKeyType = UIReturnKeyNext;
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if(textField == eMail) {
[textField resignFirstResponder];
[userName becomeFirstResponder];
}
if (textField==userName) {
[textField resignFirstResponder];
[passWord becomeFirstResponder];
}
if (textField==passWord) {
[textField resignFirstResponder];
[country becomeFirstResponder];
}
if (textField==country) {
[textField resignFirstResponder];
}
return YES;
}
If someone wants like this. I think this is the closest to the requirements asked for in question
Here is how I have implemented this one
Add accessory view for each text field for which you want the setup, using
func setAccessoryViewFor(textField : UITextField) {
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.sizeToFit()
// Adds the buttons
// Add previousButton
let prevButton = UIBarButtonItem(title: "<", style: .plain, target: self, action: #selector(previousPressed(sender:)))
prevButton.tag = textField.tag
if getPreviousResponderFor(tag: textField.tag) == nil {
prevButton.isEnabled = false
}
// Add nextButton
let nextButton = UIBarButtonItem(title: ">", style: .plain, target: self, action: #selector(nextPressed(sender:)))
nextButton.tag = textField.tag
if getNextResponderFor(tag: textField.tag) == nil {
nextButton.title = "Done"
}
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.setItems([prevButton,spaceButton,nextButton], animated: false)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar
}
Use following functions to handle taps
func nextPressed(sender : UIBarButtonItem) {
if let nextResponder = getNextResponderFor(tag: sender.tag) {
nextResponder.becomeFirstResponder()
} else {
self.view.endEditing(true)
}
}
func previousPressed(sender : UIBarButtonItem) {
if let previousResponder = getPreviousResponderFor(tag : sender.tag) {
previousResponder.becomeFirstResponder()
}
}
func getNextResponderFor(tag : Int) -> UITextField? {
return self.view.viewWithTag(tag + 1) as? UITextField
}
func getPreviousResponderFor(tag : Int) -> UITextField? {
return self.view.viewWithTag(tag - 1) as? UITextField
}
You will need to give the textFields tags in sequence in which you want the next/prev button to respond.
Solution in Swift 3.1, After connecting your textfields IBOutlets set your textfields delegate in viewDidLoad, And then navigate your action in textFieldShouldReturn
class YourViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var phoneTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.passwordTextField.delegate = self
self.phoneTextField.delegate = self
// Set your return type
self.phoneTextField.returnKeyType = .next
self.passwordTextField.returnKeyType = .done
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool{
if textField == self.phoneTextField {
self.passwordTextField.becomeFirstResponder()
}else if textField == self.passwordTextField{
// Call login api
self.login()
}
return true
}
}
I have added to PeyloW's answer in case you're looking to implement a previous/next button functionality:
- (IBAction)moveThroughTextFields:(UIBarButtonItem *)sender
{
NSInteger nextTag;
UITextView *currentTextField = [self.view findFirstResponderAndReturn];
if (currentTextField != nil) {
// I assigned tags to the buttons. 0 represent prev & 1 represents next
if (sender.tag == 0) {
nextTag = currentTextField.tag - 1;
} else if (sender.tag == 1) {
nextTag = currentTextField.tag + 1;
}
}
// Try to find next responder
UIResponder* nextResponder = [self.view viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
// I added the resign here in case there's different keyboards in place.
[currentTextField resignFirstResponder];
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[currentTextField resignFirstResponder];
}
}
Where you subclass the UIView like this:
#implementation UIView (FindAndReturnFirstResponder)
- (UITextView *)findFirstResponderAndReturn
{
for (UITextView *subView in self.subviews) {
if (subView.isFirstResponder){
return subView;
}
}
return nil;
}
#end
Hi to everyone please see this one
- (void)nextPrevious:(id)sender
{
UIView *responder = [self.view findFirstResponder];
if (nil == responder || ![responder isKindOfClass:[GroupTextField class]]) {
return;
}
switch([(UISegmentedControl *)sender selectedSegmentIndex]) {
case 0:
// previous
if (nil != ((GroupTextField *)responder).previousControl) {
[((GroupTextField *)responder).previousControl becomeFirstResponder];
DebugLog(#"currentControl: %i previousControl: %i",((GroupTextField *)responder).tag,((GroupTextField *)responder).previousControl.tag);
}
break;
case 1:
// next
if (nil != ((GroupTextField *)responder).nextControl) {
[((GroupTextField *)responder).nextControl becomeFirstResponder];
DebugLog(#"currentControl: %i nextControl: %i",((GroupTextField *)responder).tag,((GroupTextField *)responder).nextControl.tag);
}
break;
}
}
I tried to solve this problem using a more sophisticated approach based on assigning each cell (or UITextField) in a UITableView a unique tag value that can be later retrieved:
activate-next-uitextfield-in-uitableview-ios
I hope this helps!
I've just created new Pod when dealing with this stuff GNTextFieldsCollectionManager. It automatically handles next/last textField problem and is very easy to use:
[[GNTextFieldsCollectionManager alloc] initWithView:self.view];
Grabs all textfields sorted by appearing in view hierarchy (or by tags), or you can specify your own array of textFields.
A safer and more direct way, assuming:
the text field delegates are set to your view controller
all of the text fields are subviews of the same view
the text fields have tags in the order you want to progress (e.g., textField2.tag = 2, textField3.tag = 3, etc.)
moving to the next text field will happen when you tap the return button on the keyboard (you can change this to next, done, etc.)
you want the keyboard to dismiss after the last text field
Swift 4.1:
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
guard let nextTextField = textField.superview?.viewWithTag(nextTag) else {
textField.resignFirstResponder()
return false
}
nextTextField.becomeFirstResponder()
return false
}
}
I rather prefer to:
#interface MyViewController : UIViewController
#property (nonatomic, retain) IBOutletCollection(UIView) NSArray *inputFields;
#end
In the NIB file I hook the textFields in the desired order into this inputFields array. After that I do a simple test for the index of the UITextField that reports that the user tapped return:
// for UITextField
-(BOOL)textFieldShouldReturn:(UITextField*)textField {
NSUInteger index = [_inputFields indexOfObject:textField];
index++;
if (index < _inputFields.count) {
UIView *v = [_inputFields objectAtIndex:index];
[v becomeFirstResponder];
}
return NO;
}
// for UITextView
-(BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text {
if ([#"\n" isEqualToString:text]) {
NSUInteger index = [_inputFields indexOfObject:textView];
index++;
if (index < _inputFields.count) {
UIView *v = [_inputFields objectAtIndex:index];
[v becomeFirstResponder];
} else {
[self.view endEditing:YES];
}
return NO;
}
return YES;
}
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
txt_Input = [[ UITextField alloc] initWithFrame:CGRectMake(0, 10, 150, 30)];
txt_Input.tag = indexPath.row+1;
[self.array_Textfields addObject:txt_Input]; // Initialize mutable array in ViewDidLoad
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
int tag = ( int) textField.tag ;
UITextField * txt = [ self.array_Textfields objectAtIndex:tag ] ;
[ txt becomeFirstResponder] ;
return YES ;
}
I had about 10+ UITextField in my story board and the way I enabled next functionality was by creating an array of UITextField and making the next UITextField the firstResponder. Here's the implementation file:
#import "RegistrationTableViewController.h"
#interface RegistrationTableViewController ()
#property (weak, nonatomic) IBOutlet UITextField *fullNameTextField;
#property (weak, nonatomic) IBOutlet UITextField *addressTextField;
#property (weak, nonatomic) IBOutlet UITextField *address2TextField;
#property (weak, nonatomic) IBOutlet UITextField *cityTextField;
#property (weak, nonatomic) IBOutlet UITextField *zipCodeTextField;
#property (weak, nonatomic) IBOutlet UITextField *urlTextField;
#property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
#property (weak, nonatomic) IBOutlet UITextField *emailTextField;
#property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
#property (weak, nonatomic) IBOutlet UITextField *confirmPWTextField;
#end
NSArray *uiTextFieldArray;
#implementation RegistrationTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"view did load");
uiTextFieldArray = #[self.fullNameTextField,self.addressTextField,self.address2TextField,self.cityTextField,self.zipCodeTextField,self.urlTextField,self.usernameTextField,self.emailTextField,self.passwordTextField,self.confirmPWTextField];
for(UITextField *myField in uiTextFieldArray){
myField.delegate = self;
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
long index = [uiTextFieldArray indexOfObject:textField];
NSLog(#"%ld",index);
if(index < (uiTextFieldArray.count - 1)){
[uiTextFieldArray[++index] becomeFirstResponder];
}else{
[uiTextFieldArray[index] resignFirstResponder];
}
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
This worked for me in Xamarin.iOS / Monotouch.
Change the keyboard button to Next, pass the control to the next UITextField and hide the keyboard after the last UITextField.
private void SetShouldReturnDelegates(IEnumerable<UIView> subViewsToScout )
{
foreach (var item in subViewsToScout.Where(item => item.GetType() == typeof (UITextField)))
{
(item as UITextField).ReturnKeyType = UIReturnKeyType.Next;
(item as UITextField).ShouldReturn += (textField) =>
{
nint nextTag = textField.Tag + 1;
var nextResponder = textField.Superview.ViewWithTag(nextTag);
if (null != nextResponder)
nextResponder.BecomeFirstResponder();
else
textField.Superview.EndEditing(true);
//You could also use textField.ResignFirstResponder();
return false; // We do not want UITextField to insert line-breaks.
};
}
}
Inside the ViewDidLoad you'll have:
If your TextFields haven't a Tag set it now:
txtField1.Tag = 0;
txtField2.Tag = 1;
txtField3.Tag = 2;
//...
and just the call
SetShouldReturnDelegates(yourViewWithTxtFields.Subviews.ToList());
//If you are not sure of which view contains your fields you can also call it in a safer way:
SetShouldReturnDelegates(txtField1.Superview.Subviews.ToList());
//You can also reuse the same method with different containerViews in case your UITextField are under different views.
This is a simple solution in swift, with no tag using, no storyboard tricks...
Just use this extension :
extension UITextField{
func nextTextFieldField() -> UITextField?{
//field to return
var returnField : UITextField?
if self.superview != nil{
//for each view in superview
for (_, view) in self.superview!.subviews.enumerate(){
//if subview is a text's field
if view.isKindOfClass(UITextField){
//cast curent view as text field
let currentTextField = view as! UITextField
//if text field is after the current one
if currentTextField.frame.origin.y > self.frame.origin.y{
//if there is no text field to return already
if returnField == nil {
//set as default return
returnField = currentTextField
}
//else if this this less far than the other
else if currentTextField.frame.origin.y < returnField!.frame.origin.y{
//this is the field to return
returnField = currentTextField
}
}
}
}
}
//end of the mdethod
return returnField
}
}
And call it like this (for example) with your textfield delegate:
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
textField.nextTextFieldField()?.becomeFirstResponder()
return true
}
Here is a Swift 3 version of Anth0's answer. I'm posting it here to help any swift developers in wanting to take advantage of his great answer! I took the liberty of adding a return key type of "Next" when you set the associated object.
extension UITextField {
#nonobjc static var NextHashKey: UniChar = 0
var nextTextField: UITextField? {
get {
return objc_getAssociatedObject(self,
&UITextField.NextHashKey) as? UITextField
}
set(next) {
self.returnKeyType = UIReturnKeyType.next
objc_setAssociatedObject(self,
&UITextField.NextHashKey,next,.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Here is another extension that shows a possibility of using the above code to cycle through a list of UITextFields.
extension UIViewController: UITextFieldDelegate {
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let next = textField.nextTextField else {
textField.resignFirstResponder()
return true
}
next.becomeFirstResponder()
return false
}
}
And then in your ViewController or wherever, you can setup your textfields like so...
#IBOutlet fileprivate weak var textfield1: UITextField!
#IBOutlet fileprivate weak var textfield2: UITextField!
#IBOutlet fileprivate weak var textfield3: UITextField!
...
[textfield1, textfield2, textfield3].forEach{ $0?.delegate = self }
textfield1.nextTextField = textfield2
textfield2.nextTextField = textfield3
// We don't assign a nextTextField to textfield3 because we want
// textfield3 to be the last one and resignFirstResponder when
// the return button on the soft keyboard is tapped.
in textFieldShouldReturn you should check that the textfield you are currently on is not the last one when they click next and if its n ot dont dismiss the keyboard..
This is an old post, but has a high page rank so I'll chime in with my solution.
I had a similar issue and ended up creating a subclass of UIToolbar to manage the next/previous/done functionality in a dynamic tableView with sections: https://github.com/jday001/DataEntryToolbar
You set the toolbar as inputAccessoryView of your text fields and add them to its dictionary. This allows you to cycle through them forwards and backwards, even with dynamic content. There are delegate methods if you want to trigger your own functionality when textField navigation happens, but you don't have to deal with managing any tags or first responder status.
There are code snippets & an example app at the GitHub link to help with the implementation details. You will need your own data model to keep track of the values inside the fields.
Without usings tags and without adding a property for nextField/nextTextField, you can try this to emulate TAB, where "testInput" is your current active field:
if ([textInput isFirstResponder])
[textInput.superview.subviews enumerateObjectsAtIndexes:
[NSIndexSet indexSetWithIndexesInRange:
NSMakeRange([textInput.superview.subviews indexOfObject:textInput]+1,
[textInput.superview.subviews count]-[textInput.superview.subviews indexOfObject:textInput]-1)]
options:0 usingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
*stop = !obj.hidden && [obj becomeFirstResponder];
}];
if ([textInput isFirstResponder])
[textInput.superview.subviews enumerateObjectsAtIndexes:
[NSIndexSet indexSetWithIndexesInRange:
NSMakeRange(0,
[textInput.superview.subviews indexOfObject:textInput])]
options:0 usingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
*stop = !obj.hidden && [obj becomeFirstResponder];
}];

Resources