iOS 怎么在项目里面嵌入C的代码

我们知道 xCode 是完全兼容 OC, C, swift 的。但是C语言在里面应该怎么写呢?

interface 是OC的接口部分;

implement 是OC的实现部分;

所以 C语言 不建议写在里面。

应该 特别的找一个类(可以是View 可以是model 可以是controller 总之都可以),在OC接口和实现的外面 写入C的实现即可。如:

//
//  BaseVC.h
//  embedC
//
//  Created by lc-macbook pro on 2017/6/12.
//  Copyright © 2017年 mac. All rights reserved.
//

#import <UIKit/UIKit.h>

UILabel *createLbl(UIFont *font,NSString *text);

UIButton *createButton(NSString *title, UIFont *font, UIColor *titleColor);

UITextField *createField(NSString *placeHold,UIFont *font);


@interface BaseVC : UIViewController


@end

  

//
//  BaseVC.m
//  embedC
//
//  Created by lc-macbook pro on 2017/6/12.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "BaseVC.h"


UILabel *createLbl(UIFont *font,NSString *text)
{
    UILabel *lbl=[UILabel new];
    lbl.backgroundColor=[UIColor clearColor];
    lbl.font= font;
    lbl.text = text;
    lbl.textAlignment=NSTextAlignmentLeft;
    return lbl;
}
UIButton *createButton(NSString *title, UIFont *font, UIColor *titleColor)
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTintColor:[UIColor clearColor]];
    btn.titleLabel.font = font;
    return btn;
}

UITextField *createField(NSString *placeHold,UIFont *font)
{
    UITextField *textfield=[[UITextField alloc]init];
    textfield.font=font;
    textfield.placeholder=placeHold;
    textfield.leftViewMode=UITextFieldViewModeAlways;
    textfield.rightViewMode = UITextFieldViewModeAlways;
    textfield.clearButtonMode=UITextFieldViewModeWhileEditing;
    return textfield;
}

@interface BaseVC ()

@end

@implementation BaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

  

引入这个类的头文件, 就可以在任何地方, 调用自己写的接口啦, 是不是很简单?

//
//  ViewController.m
//  embedC
//
//  Created by lc-macbook pro on 2017/6/12.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UILabel *lbl = createLbl([UIFont systemFontOfSize:20], @"用 C语言 封装创建Label的API");
    lbl.frame = CGRectMake(100, 100, 300, 40);
    [self.view addSubview:lbl];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

  

看下效果:github 地址:embedC

原文地址:https://www.cnblogs.com/saytome/p/6994193.html