您的位置:首页 > 移动开发 > IOS开发

iOS蓝牙4.0的打印功能的简单实现

2017-09-25 14:03 323 查看
由于前段时间的项目开发需要,做了个蓝牙打印的功能,基于项目开发复杂度和开发时间成本的考虑,最终只实现了蓝牙4.0的打印功能(需要iPhone4s及其以上设备,无需MFI认证)。为了使得代码更加简洁清晰,在此我专门抽了一个蓝牙打印的管理类出来。话不多说,直接上代码。

蓝牙管理对象.h文件代码:

/**
*
* CoreBluetooth框架只针对蓝牙4.0开发
蓝牙2.0开发需要蓝牙设备厂商获得苹果的MFI认证,一般要填写一些应用信息给厂商由厂商添加验证,并且厂商提供相关的开发包(比较麻烦,没搞过)
*
*所有的蓝牙连接断开发送数据等操作都是在APP里面完成,不需要通过任何系统设置连接
*
*
**/

#import <Foundation/Foundation.h>

@protocol BlueToothMangerDelegate <NSObject>

@optional;
- (void)didDiscoverBlueToothDeviceWithDevices:(NSMutableArray *)devices;    //发现蓝牙设备
- (void)didConnectToBlueToothDevice;

@end

@interface BlueToothManger : NSObject

@property (nonatomic,assign)float scanTime;                     //扫描时间
@property (nonatomic,assign)float connectTime;                  //连接时间
@property (nonatomic,weak)id<BlueToothMangerDelegate> delegate;

/*
*获取打印机管理对象
**/
+ (instancetype)sharedBlueToothManger;

/*
*扫描蓝牙设备
**/
- (void)scanBlueToothDevices;

/*
*连接指定蓝牙设备
**/
- (void)connectBlueToothDevice:(id)device;

/*
*发送数据
**/
- (void)sendData;

/*
*断开连接
**/
- (void)disconnect;

@end


蓝牙管理对象.m文件代码:

//
//  BlueToothManger.m
//  BlueToothDemo
//
//  Created by weeget on 17/4/26.
//  Copyright © 2017年 weeget. All rights reserved.
//

#import "BlueToothManger.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "MBProgressHUD+MJ.h"

#define MAX_CHARACTERISTIC_VALUE_SIZE 20      //每次发送的字节数(有限制,具体多少好像跟蓝牙设备有关)

/**
*UUID可百度蓝牙UUID,可用于手机识别每台蓝牙设备
**/
#define kServiceUUID @"E7810A71-73AE-499D-8C15-FAA9AEF0C3F2"          //打印的服务id(大部分蓝牙打印机通用)
#define kCharacteristicUUID @"BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F"   //打印的特征id (大部分蓝牙打印机通用)

#pragma mark -- 简单的打印指令
//打印对齐方式
typedef enum {

LeftAlignPrintType = 0,
CenterAlignPrintType = 1,
RightAlignPrintType = 2,

} BlueToothPrintAlignType;

//是否加粗
typedef enum {

WithOutBoldType = 0x00,
WithBoldType = 0x08,

} BlueToothPrin
4000
tBoldType;

//是否放大打印
typedef enum {

EnlargeFontType = 0x11,
NormalFontType = 0x00,

}BlueToothEnlargeType;

@interface BlueToothManger ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (nonatomic,strong)CBCentralManager *blueToothManager;   //蓝牙连接管理
@property (nonatomic,strong)CBPeripheral *connectPeripheral;      //连接的蓝牙设备
@property (nonatomic,strong)CBCharacteristic *characteristic;     //通信的蓝牙设备特征

@property (nonatomic,assign)NSInteger bluetoothState;             //手机蓝牙状态
@property (nonatomic,assign)BOOL isBlueConnected;                 //蓝牙设备是否连接着

@property (nonatomic,strong)NSMutableArray *devices;              //扫描到的蓝牙设备数组
@property (nonatomic,strong)NSMutableArray *sendDataArray;        //要发送的数据数组

@property (nonatomic,strong)NSTimer *scanTimer;                   //扫描定时器
@property (nonatomic,strong)NSTimer *connectTimer;                //连接定时器

@end

@implementation BlueToothManger

+ (instancetype)sharedBlueToothManger
{

static BlueToothManger *manager = nil;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{

manager = [[self alloc]init];
manager.scanTime = 20.0;    //默认扫描时间
manager.connectTime = 10.0;

});

return manager;
}

/*
*扫描蓝牙设备
**/
- (void)scanBlueToothDevices
{
NSLog(@"搜索中···");
//    [MBProgressHUD showMessage:@"搜索中···" toView:[UIApplication sharedApplication].delegate.window];
[self.devices removeAllObjects];

self.connectPeripheral = nil;
self.isBlueConnected = NO;
self.characteristic = nil;
if (self.connectPeripheral) {
[self.blueToothManager cancelPeripheralConnection:self.connectPeripheral];
}

if ([self.delegate respondsToSelector:@selector(didDiscoverBlueToothDeviceWithDevices:)]) {
[self.delegate didDiscoverBlueToothDeviceWithDevices:self.devices];
}

if (!self.blueToothManager) {

self.blueToothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];  //首次创建的话会弹框请求蓝牙授权

}

/**避免获取不到正确的手机蓝牙状态,这个问题莫名其妙,不是很清楚原理,去掉之后就不行了**/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

if (self.bluetoothState == CBManagerStatePoweredOff) {

NSLog(@"请检查手机蓝牙");
[MBProgressHUD showError:@"请检查手机蓝牙" toView:[UIApplication sharedApplication].delegate.window];

}else{

NSLog(@"搜索中···");
//            [MBProgressHUD showMessage:@"搜索中···" toView:[UIApplication sharedApplication].delegate.window];
/**加延时是为了避免一些奇怪的错误,这个原因我也不是很清楚**/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

[self.blueToothManager scanForPeripheralsWithServices:nil options:nil];  //扫描设备
self.scanTimer = [NSTimer scheduledTimerWithTimeInterval:self.scanTime target:self selector:@selector(scanTimeOut:) userInfo:nil repeats:NO];

});
}

});

}

/*
*连接指定的蓝牙设备
**/
- (void)connectBlueToothDevice:(id)device
{
if (!device) {
return;
}

NSLog(@"停止扫描");
[self scanTimeOut:self.scanTimer];

[MBProgressHUD showMessage:@"连接中···" toView:[UIApplication sharedApplication].delegate.window];
_connectPeripheral = device;

[self.blueToothManager connectPeripheral:device options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];

self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:self.connectTime target:self selector:@selector(connectTimeOut:) userInfo:nil repeats:NO];
}

/*
*断开连接
**/
- (void)disconnect
{
if (self.connectPeripheral) {
[self.blueToothManager cancelPeripheralConnection:self.connectPeripheral];
}
}

/*
*发送数据,这里只是做一个简单的文本打印测试,打印数据和打印格式设置可以由外面传进来,图片打印复杂点,后面再贴代码
**/
- (void)sendData
{

if (self.connectPeripheral && self.characteristic) {

NSLog(@"发送数据");
[MBProgressHUD showSuccess:@"发送数据" toView:[UIApplication sharedApplication].delegate.window];
[self printContent:@"打印测试数据\n\n\n"];

}
}

/*
*循环发送数据,每次发送长度不超过 MAX_CHARACTERISTIC_VALUE_SIZE
**/
- (void)printContent:(NSString *)printContent
{

NSData  *data = nil;
NSUInteger i;
NSUInteger strLength;
NSUInteger cellCount;
NSUInteger cellMin;
NSUInteger cellLen;

NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

strLength = [printContent length];
if (strLength < 1) {
return;
}

cellCount = (strLength%MAX_CHARACTERISTIC_VALUE_SIZE)?(strLength/MAX_CHARACTERISTIC_VALUE_SIZE + 1):(strLength/MAX_CHARACTERISTIC_VALUE_SIZE);

for (i=0; i<cellCount; i++) {
cellMin = i*MAX_CHARACTERISTIC_VALUE_SIZE;
if (cellMin + MAX_CHARACTERISTIC_VALUE_SIZE > strLength) {
cellLen = strLength-cellMin;
}
else {
cellLen = MAX_CHARACTERISTIC_VALUE_SIZE;
}

NSRange rang = NSMakeRange(cellMin, cellLen);
NSString *strRang = [printContent substringWithRange:rang];
//        NSLog(@"print:%@", strRang);

data = [strRang dataUsingEncoding: enc];
//        NSLog(@"print:%@", data);

[self.connectPeripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];

}
}

/**
*超过扫描时间
*
**/
- (void)scanTimeOut:(NSTimer *)timer
{

NSLog(@"停止扫描");
[MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].delegate.window animated:NO];

if (timer) {
[timer invalidate];
timer = nil;
}

if (self.blueToothManager) {
[MBProgressHUD showError:@"停止扫描" toView:[UIApplication sharedApplication].delegate.window];
[self.blueToothManager stopScan];

}

}

/*连接超时*/
- (void)connectTimeOut:(NSTimer *)timer
{
if (timer) {
[timer invalidate];
timer = nil;
}
[MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].delegate.window animated:NO];
[MBProgressHUD showError:@"连接失败" toView:[UIApplication sharedApplication].delegate.window];
}

#pragma mark -- CBCentralManagerDelegate
/*
*扫描到新的蓝牙设备
**/
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
//advertisementData --- 广播包数据,苹果是不能直接获取设备的MAC地址的,有些厂家会将MAC地址放在广播包数据里面,但比较少
//苹果蓝牙4.0 一般都是通过UUID来区分每台蓝牙设备
NSLog(@"%@",advertisementData);
//判断是否可连接
if ([advertisementData[@"kCBAdvDataIsConnectable"] boolValue]) {

if(![self.devices containsObject:peripheral]){
[self.devices addObject:peripheral];
if ([self.delegate respondsToSelector:@selector(didDiscoverBlueToothDeviceWithDevices:)]) {
[self.delegate didDiscoverBlueToothDeviceWithDevices:self.devices];
}
}
}
}

/*
*连接到蓝牙设备,销毁连接定时器
**/
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
if (self.connectTimer) {
[self.connectTimer invalidate];
self.connectTimer = nil;
}

self.connectPeripheral = peripheral;
self.isBlueConnected = YES;
peripheral.delegate = self;
[peripheral discoverServices:nil];//查看蓝牙设备所拥有的所有服务,蓝牙设备可能有一个或者一个以上的服务
NSLog(@"成功连接蓝牙设备");

}

/**
*
*断开蓝牙连接
*
**/
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
self.connectPeripheral = nil;
self.isBlueConnected = NO;
self.characteristic = nil;
[MBProgressHUD showError:@"断开连接" toView:[UIApplication sharedApplication].delegate.window];
}

/**
*
*关闭手机蓝牙 关闭了蓝牙设备
*
**/
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"连接失败");
[MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].delegate.window animated:NO];
[MBProgressHUD showError:@"连接失败" toView:[UIApplication sharedApplication].delegate.window];

if (self.connectTimer) {
[self.connectTimer invalidate];
self.connectTimer = nil;
}

self.connectPeripheral = nil;
self.isBlueConnected = NO;
self.characteristic = nil;

}

/**
*一创建蓝牙管理对象马上会调用该方法
*监测手机蓝牙状态
*
**/
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{

self.bluetoothState = central.state;

if (central.state != CBManagerStatePoweredOn) {
self.connectPeripheral = nil;
self.isBlueConnected = NO;
self.characteristic = nil;
}

//    switch (central.state) {
//        case 0:
//            [MBProgressHUD showError:@"初始化中,请稍后……"];
//            break;
//        case 1:
//            [MBProgressHUD showError:@"手机不支持蓝牙功能,请检查系统设置"];
//            break;
//        case 2:
//            [MBProgressHUD showError:@"手机蓝牙未授权,请检查系统设置"];
//            break;
//        case 3:
//            [MBProgressHUD showError: @"手机蓝牙未授权,请检查系统设置"];
//            break;
//        case 4:
//            [MBProgressHUD showError:@"手机尚未打开蓝牙,请在设置中打开"];
//            break;
//        case 5:
//            [MBProgressHUD showError:@"蓝牙已经成功开启,请稍后再试"];
//            break;
//        default:
//            break;
//    }

}

#pragma mark -- CBPeripheralDelegate
/*
*扫描设备服务成功,获取当前连接的蓝牙所有服务
*[peripheral discoverServices:nil] 成功回调方法
*
**/
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{

for (CBService *service in peripheral.services)
{

NSLog(@"%@",service);

}

//    for (CBService *service in peripheral.services)
//    {
//
//        if ([service.UUID.UUIDString isEqualToString:kServiceUUID]) {
//
//            [peripheral discoverCharacteristics:nil forService:service];
//            break;
//        }
//
//    }

[peripheral discoverCharacteristics:nil forService:peripheral.services.firstObject];

}

/**
*
*获取蓝牙设备某个服务的下面的所有特征,一个服务下面有一个或者一个以上的特征
*[peripheral discoverCharacteristics:nil forService:service] 成功会回调该方法
*
**/
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{

for (CBCharacteristic *characteristic in service.characteristics) {

NSLog(@"%@",characteristic);

}

//    for (CBCharacteristic *characteristic in service.characteristics) {
//
//        if ([characteristic.UUID.UUIDString isEqualToString:kCharacteristicUUID]) {
//
//            self.characteristic = characteristic;
//
//            break;
//
//        }
//    }
self.characteristic = service.characteristics.firstObject;
[MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].delegate.window animated:NO];
[MBProgressHUD showSuccess:@"成功连接蓝牙设备" toView:[UIApplication sharedApplication].delegate.window];

if ([self.delegate respondsToSelector:@selector(didConnectToBlueToothDevice)]) {
[self.delegate didConnectToBlueToothDevice];
}

}

/*
*成功发送数据
*
**/
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"write value");
}

#pragma mark -- LazyLoad
- (NSMutableArray *)devices
{

if (!_devices) {

_devices = [[NSMutableArray alloc]init];

}

return _devices;
}

- (NSMutableArray *)sendDataArray
{
if (!_sendDataArray) {

_sendDataArray = [[NSMutableArray alloc]init];

}

return _sendDataArray;
}

@end


视图控制器.m代码:

#import "ViewController.h"
#import "BlueToothManger.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BlueToothSelectView.h"

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define Duration 0.3

@interface ViewController ()<BlueToothMangerDelegate,BlueToothSelectViewDelegate>

@property (nonatomic,strong)NSArray *operatedBtnArr;          //操作按钮
@property (nonatomic,strong)BlueToothSelectView *selectView;

@end

@implementation ViewController

#pragma mark -- SystemMethod
- (void)viewDidLoad {
[super viewDidLoad];
[self buildView];
[BlueToothManger sharedBlueToothManger].delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}

#pragma mark -- CustomMethod
- (void)buildView
{
self.title = @"蓝牙控制";
self.view.backgroundColor = [UIColor whiteColor];
self.automaticallyAdjustsScrollViewInsets = NO;

UIView *btnsBgView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 50, ScreenWidth, 50)];
btnsBgView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:btnsBgView];

CGFloat btnWidth = (ScreenWidth - 10 * (self.operatedBtnArr.count + 1)) / self.operatedBtnArr.count;

for (int i = 0;i < self.operatedBtnArr.count;i ++) {

NSString *title = self.operatedBtnArr[i];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(10 + (10 + btnWidth) * i, 5, btnWidth, 40);
btn.titleLabel.font = [UIFont systemFontOfSize:15];
[btn setTitle:title forState:UIControlStateNormal];
[btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
btn.backgroundColor = [UIColor whiteColor];
btn.layer.borderWidth = 0.5;
btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
[btn addTarget:self action:@selector(didClickBtnWithBtn:) forControlEvents:UIControlEventTouchUpInside];
[btnsBgView addSubview:btn];

}
}

- (void)didClickBtnWithBtn:(UIButton *)btn
{
if ([btn.currentTitle isEqualToString:@"扫描"]) {
self.selectView = [[BlueToothSelectView alloc]initWithFrame:self.view.bounds];
self.selectView.delegate = self;
[self.selectView showView];

[BlueToothManger sharedBlueToothManger].scanTime = 20.0;
[[BlueToothManger sharedBlueToothManger] scanBlueToothDevices];
}else if ([btn.currentTitle isEqualToString:@"打印"]){
[[BlueToothManger sharedBlueToothManger] sendData];
}else
9986
if ([btn.currentTitle isEqualToString:@"断开连接"]){
[[BlueToothManger sharedBlueToothManger] disconnect];
}

}

#pragma mark -- BlueToothMangerDelegate
/*
*扫描到新的打印设备
**/
- (void)didDiscoverBlueToothDeviceWithDevices:(NSMutableArray *)devices
{
[self.selectView didDiscoverBlueToothDeviceWithDevices:devices];
}

- (void)didConnectToBlueToothDevice
{
[self.selectView removeFromSuperview];
}

#pragma mark -- BlueToothSelectViewDelegate
/*
*连接蓝牙设备
**/
- (void)blueToothDidSelectWithDevice:(CBPeripheral *)peripheral
{
[[BlueToothManger sharedBlueToothManger] connectBlueToothDevice:peripheral];
}

#pragma mark -- LazyLoad
- (NSArray *)operatedBtnArr
{
if (!_operatedBtnArr) {
_operatedBtnArr = @[@"扫描",@"断开连接"];
}
return _operatedBtnArr;
}


扫描到的蓝牙设备列表显示视图BlueToothSelectView.h文件:

//
//  BlueToothSelectView.m
//  BlueToothDemo
//
//  Created by ZZQ on 2017/7/3.
//  Copyright © 2017年 weeget. All rights reserved.
//

#import "BlueToothSelectView.h"

#define kReusedId @"cell"
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height

#define kMaxVisibleCount 4

#define kItemHeight 44

@interface BlueToothSelectView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UIView *bgView;
@property (nonatomic,strong)UIButton *disappearBtn;

@property (nonatomic,strong)UILabel *titleLbl;
@property (nonatomic,strong)UITableView *tableView;           //蓝牙设备列表
@property (nonatomic,strong)NSMutableArray *devices;          //设备数组

@end

@implementation BlueToothSelectView

- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {

_disappearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_disappearBtn.frame = self.frame;
[self addSubview:_disappearBtn];
_disappearBtn.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.3];
[_disappearBtn addTarget:self action:@selector(disappearView) forControlEvents:UIControlEventTouchUpInside];

_bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0.8 * ScreenWidth, kItemHeight * 2)];
_bgView.backgroundColor = [UIColor whiteColor];
[_disappearBtn addSubview:_bgView];
_bgView.layer.cornerRadius = 8.0;
_bgView.clipsToBounds = YES;
_bgView.center = _disappearBtn.center;
_bgView.layer.borderColor = [UIColor lightGrayColor].CGColor;
_bgView.layer.borderWidth = 0.5;

_titleLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _bgView.frame.size.width, kItemHeight)];
_titleLbl.text = @"连接蓝牙";
_titleLbl.font = [UIFont systemFontOfSize:16];
_titleLbl.textColor = [UIColor darkGrayColor];
_titleLbl.textAlignment = NSTextAlignmentCenter;
[_bgView addSubview:_titleLbl];

UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, kItemHeight - 0.5, _bgView.frame.size.width, 0.5)];
lineView.backgroundColor = [UIColor lightGrayColor];
[_titleLbl addSubview:lineView];

[_bgView addSubview:self.tableView];

}
return self;
}

- (void)showView
{
CAKeyframeAnimation * animation;
animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
animation.duration = 0.30;
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeForwards;
NSMutableArray *values = [NSMutableArray array];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
animation.values = values;
[self.bgView.layer addAnimation:animation forKey:nil];

UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *topVC = appRootVC;
while (topVC.presentedViewController) {
topVC = topVC.presentedViewController;
}

[topVC.view addSubview:self];
}

- (void)disappearView
{
if ([self.delegate respondsToSelector:@selector(blueToothDidSelectWithDevice:)]) {
[self.delegate blueToothDidSelectWithDevice:nil];
}
[self removeFromSuperview];
}

- (void)didDiscoverBlueToothDeviceWithDevices:(NSMutableArray *)devices
{
self.devices = devices;

if (devices.count > kMaxVisibleCount) {
self.bgView.frame = CGRectMake(0, 0, 0.8 * ScreenWidth, kItemHeight * (kMaxVisibleCount  + 1));
}else{
if (devices.count == 0) {
self.bgView.frame = CGRectMake(0, 0, 0.8 * ScreenWidth, kItemHeight * (devices.count + 2));
}else{
self.bgView.frame = CGRectMake(0, 0, 0.8 * ScreenWidth, kItemHeight * (devices.count + 1));
}
}
self.bgView.center = _disappearBtn.center;
self.tableView.frame = CGRectMake(0, kItemHeight, 0.7  * ScreenWidth, _bgView.frame.size.height - kItemHeight);
[self.tableView reloadData];

}

#pragma mark -- Delegate
#pragma mark -- UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.devices.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReusedId];
cell.selectionStyle = UITableViewCellSelectionStyleNone;

CBPeripheral *device = self.devices[indexPath.row];

cell.textLabel.text = device.name;
cell.detailTextLabel.text = device.identifier.UUIDString;

return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(blueToothDidSelectWithDevice:)]) {
CBPeripheral *device = self.devices[indexPath.row];
[self.delegate blueToothDidSelectWithDevice:device];
}
}

#pragma mark -- LazyLoad
- (UITableView *)tableView
{
if (!_tableView) {

_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kItemHeight, 0.8  * ScreenWidth, kItemHeight) style:UITableViewStylePlain];
_tableView.showsVerticalScrollIndicator = NO;
_tableView.delegate = self;
_tableView.dataSource = self;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kReusedId];
}

return _tableView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: