IOS 字符串生成二维码

生成二维码的类很多,本文采用的是Libqrencode,此第三方框架仅仅作为生成二维码用,不能扫描,如果需要扫描的请绕行别处。

.m的实现代码如下,Libqrencode是用C编写,因此调用方法也比较简单,

#import "ViewController.h"
#import "QRCodeGenerator.h"
@interface ViewController ()
{
    NSString *string;
    CGRect rx;
    UIImageView *imageView;
    UITextField *field;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor orangeColor]];
    rx = [UIScreen mainScreen].bounds;
    field = [[UITextField alloc]initWithFrame:CGRectMake(10, 30, rx.size.width-20, 30)];
    [field setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:field];
    [field setDelegate:self];

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(rx.size.width/2-50, 70, 100, 30)];
    [btn.layer setCornerRadius:5];
    [btn setBackgroundColor:[UIColor blueColor]];
    [btn setTitle:@"生成二维码" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    //设置二维码显示的imageView
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(rx.size.width/2-150, 150, 300, 300)];
    [imageView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:imageView];
}
#pragma 点击按钮生成二维码方法
-(void)action
{
    string = field.text;
    NSLog(@"++++%@",string);
    //这句话就是调用的Libqrencode,实现了生成二维码,并把生成后的图片加载到imageView上
    imageView.image = [QRCodeGenerator qrImageForString:string imageSize:imageView.bounds.size.width];
    
}
#pragma 键盘失去第一响应者,(隐藏键盘) PS:需要在.h的文件中添加textField的代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [field resignFirstResponder];    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    return YES;
}

@end


Libqrencode下载地址

你可能感兴趣的:(IOS)