Swift调用Objective-C编写的代码(颜色选择器KKColorListPicker调用)

1,首先在项目里导入KKColorListPicker的源码(整个文件夹,在项目上有键“Add Files To XXX”).
2,手工创建桥接头文件bridge.h来包含需要引用的Objective-C头文件,内容如下:
//KKColorsSchemeType.h已经包含在KKColorListViewController.h
#import "KKColorListViewController.h"
#import "KKColor.h"
3,选择项目,在Build Setting -> Swift Compiler-Code generation -> Objective-C Bridging Header设置里添加bridge.h,如下图所示:
(直接把bridge.h拖进去)
Swift调用Objective-C编写的代码(颜色选择器KKColorListPicker调用)_第1张图片
屏幕快照 2017-03-15 下午2.32.51.png
import UIKit

class ViewController: UIViewController,KKColorListViewControllerDelegate {

    var viewColor:KKColorListViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //初始化颜色选择面板
        //这个颜色选择面板是用OC开发,我们导入头文件后就能在Swift里调用了
        viewColor = KKColorListViewController(schemeType:KKColorsSchemeType.crayola)
        //此类实现了颜色选择面板的代理协议,并重载了选择颜色和关闭2个回调函数
        viewColor.delegate = self
        
        //创建一个按钮
        let button:UIButton = UIButton(type: .system)
        //设置按钮位置和大小
        button.frame=CGRect(x: 10, y: 50, width: 100, height: 30)
        //设置按钮文字
        button.setTitle("选择背景色", for:UIControlState.normal)
        button.addTarget(self, action: #selector(btnClick(_ :)), for: .touchUpInside)
        self.view.addSubview(button);
        
    }
    func btnClick(_ :UIButton)
    {
        //显示颜色选择面板
        self.present(viewColor, animated: true, completion: nil)
    }
    func colorListController(_ controller:KKColorListViewController,didSelect color:KKColor)
    {
        //关闭颜色选择器视图
        viewColor.dismiss(animated: true, completion:nil)
        //设置当前视图的背景颜色为用户选择的颜色
        self.view.backgroundColor = color.uiColor()
    }
    //用户在颜色选择器视图里点击了关闭
    func colorListPickerDidComplete(_ controller:KKColorListViewController)
    {
        //只需要关闭颜色选择器视图
        viewColor.dismiss(animated: true, completion:nil)
    }

    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

你可能感兴趣的:(Swift调用Objective-C编写的代码(颜色选择器KKColorListPicker调用))