代码改变世界

iOS 为系统方法添加自定义功能

2016-09-06 15:05  TemptationM  阅读(266)  评论(0)    收藏  举报

     在开发中很多时候不同的界面却需要实现相同的需求, 比如每个界面都需要改变背景色、每个界面都需要隐藏导航栏左侧item的title等等。。

解决这种问题有很多办法, 也许你会想到继承, 但在这里我们用另一种简单的方法来不动声色的实现, 我们需要这个方法 :

/** 
 * Exchanges the implementations of two methods.
 * 
 * @param m1 Method to exchange with second method.
 * @param m2 Method to exchange with first method.
 * 
 * @note This is an atomic version of the following:
 *  \code 
 *  IMP imp1 = method_getImplementation(m1);
 *  IMP imp2 = method_getImplementation(m2);
 *  method_setImplementation(m1, imp2);
 *  method_setImplementation(m2, imp1);
 *  \endcode
 */
OBJC_EXPORT void method_exchangeImplementations(Method m1, Method m2) 
     __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

这个方法是将两个方法的功能进行交换

 

 

这里我们以 隐藏各个界面左侧返回键的title 为例

解决此问题的方法 实现代码为: (这些代码我是写在一个UIViewController的category里面)

- (void)backTitleDestory_viewDidLoad
{
    [self backTitleDestory_viewDidLoad]; 这里看似是自己调自己, 其实我们在上个方法里面已经将它与viewDidLoad进行了交换, 现在其实是调用的viewDidLoad
    if (!self.navigationItem.title) {
        self.navigationItem.title = @""; // 当title为nil时,backItem会显示“返回”
    }
    self.navigationController.navigationBar.topItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

+ (void)replaceInstanceSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector
{
    Method originalMethod = class_getInstanceMethod(self, originalSelector);
    Method modifiedMethod = class_getInstanceMethod(self, modifiedSelector);
    method_exchangeImplementations(originalMethod, modifiedMethod);
}

+ (void)destoryBackBarButtonItemTitle 
{
    [self replaceInstanceSelector:@selector(viewDidLoad) withSelector:@selector(backTitleDestory_viewDidLoad)];
}

 

接下来只需在Appdelegate里面调用这个方法

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    [UIViewController destoryBackBarButtonItemTitle];return YES;
}

 

搞定!  就这样  程序就是在Appdelegate里面就已经将系统的viewDidLoad换成了我们自己写的一个方法,然后在自己的方法里面调用“自己”(其实自己的方法已经是viewDidLoad)

这样下来效果就是在以后的每个viewDidLoad里面都添加了一些固定功能的方法

 

是的 这样就在不知不觉中修改了所有界面的共同需求