我们如何在自定义UIView类中调用操作?需要在所有View Controller中重用UIView类

时间:2016-03-28 12:19:33

标签: ios objective-c uiview uiviewcontroller uibutton

我创建了一个自定义的UIView类。我想在调用backButton时调用一个动作。需要在所有视图控制器中重用此UIView类以及操作。我可以在UIView类中自己编写或查看控制器吗?

#import "CustomView.h"

@implementation CustomView

- (instancetype)init {

   if(self = [super init]){
    //-------------------custom headerView----------------
    self.headerView = [[UIView alloc]init];
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    self.headerView.backgroundColor = [UIColor redColor];
    [self addSubview:self.headerView];

    self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(5,13, 12, 16)];
    [self.backButton setImage:[UIImage imageNamed:@"back-btn.png"]
                     forState:UIControlStateNormal];
    [self.backButton addTarget:self
                        action:@selector(backButtonAction)
              forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];
   }
   return self;
}

BackButton Action

-(void)backButtonAction{
   [[self navigationController] popViewControllerAnimated:YES];
}

1 个答案:

答案 0 :(得分:4)

它很简单 您必须为UIViewController UIViewController+Additions制作类别

  1. 点击File - > New - > File

  2. 点击Objective-C fileSources下的iOS,然后点击下一步

  3. 现在在File Type:下选择Category

  4. 然后设置文件名:Additions并设置类:UIViewController

  5. <强>的UIViewController + Additions.h
    首先在.h &gt;&gt;

    中创建您的后退按钮功能
    -(void)addBackButton;
    

    <强>的UIViewController + Additions.m

    -(void)addBackButton
    {
        self.navigationItem.leftBarButtonItem = nil;
        UIButton *aBtn = [UIButton buttonWithType:UIButtonTypeCustom];
       // [aBtn setTitle:@"Back" forState:UIControlStateNormal];
        [aBtn setImage:[UIImage imageNamed:@"back-btn.png"] forState:UIControlStateNormal];
        [aBtn setFrame:CGRectMake(0, 0,50, 64)];
        [aBtn.titleLabel setFont:[UIFont systemFontOfSize:18.0]];
        aBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        aBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        aBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
        [aBtn setTitleColor:[UIColor colorWithRed:1/255.0 green:65/255.0 blue:96/255.0 alpha:1.0] forState:UIControlStateNormal];
    
            [aBtn addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
        UIBarButtonItem *aBarBtn = [[UIBarButtonItem alloc]initWithCustomView:aBtn];
        self.navigationItem.leftBarButtonItem = aBarBtn;
    }
    
    -(void)backButtonAction
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    

    像这样使用:

    只需在任何viewcontroller类#import "UIViewController+Additions.h"

    中导入类别
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
         [self addBackButton];
    }