码迷,mamicode.com
首页 > 其他好文 > 详细

NSClassFromString 和 遍历UIView获取她所在的UIViewController的tips

时间:2015-11-17 17:02:48      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

一、NSClassFromString是NSObjCRuntime.h的方法

FOUNDATION_EXPORT Class __nullable NSClassFromString(NSString *aClassName);
Description:Obtains a class by name.The name of a class.
Parameters:aClassName The name of a class
Returns:The class object named by aClassName , or nil if no class by that name is currently loaded

通过NSClassFromString创建类,可以使用里氏代换原则区创建子类

假设有一个类名为:DBHelper

一般创建她的Instance:

[[DBHelper alloc] init];

但是如果用NSClassFromString创建实体的话:

NSString * className = @"DBHelper";
Class class = NSClassFromString(className);
if (class)
{
      DBHelper * dbHelper = class.new;          
}

或者:

NSString * className = @"DBHelper";
id dbHelperObj = [[NSClassFromString(className) alloc] init];

这样写很明显的好处:

1.使用的时候,不必担心因为类不存在而报错,因为返回空的时候是nil,所以不会导致程序崩溃

2.方便使用里氏代换原则的模式

二、在自定义的UIView(hex)的控件类里面,如何获取她所在当前的UIViewController的小技巧

1.首先,确保你创建的类继承自UIView

2.其次,我们都知道大部分的UIKit类继承自UIResponder。

啥是UIResponder?

UIResponder中有很多我们耳熟能详的几种方法:

1》nextResponder

- (UIResponder * _Nullable)nextResponder
Description:    
Returns the receiver??s next responder, or nil if it has none.
The next object in the responder chain to be presented with an event for handling.
Returns:
The next object in the responder chain to be presented with an event for handling.

2》响应链中的操作

- (BOOL)canBecomeFirstResponder;    // default is NO
- (BOOL)becomeFirstResponder;

- (BOOL)canResignFirstResponder;    // default is YES
- (BOOL)resignFirstResponder;

- (BOOL)isFirstResponder;

3》touch事件

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesCancelled:(nullable NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEstimatedPropertiesUpdated:(NSSet * _Nonnull)touches NS_AVAILABLE_IOS(9_1);

etc.

3.所以我们用到UIResponder中nextResponder方法

for(UIView * view = self; view; view = view.superview)
{
       UIResponder * nextResponder = [view nextResponder];
       if  ([nextResponder iskindOfClass:[UIViewController class]])
       {
             return (UIViewController *)nextResponder;
       }            
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

其实,还有回到跟视图的方法,你们可以试试写出来

NSClassFromString 和 遍历UIView获取她所在的UIViewController的tips

标签:

原文地址:http://www.cnblogs.com/R0SS/p/4972079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!