1. 程式人生 > >輸入文字生成二維碼

輸入文字生成二維碼

#import "ViewController.h"
#import "QRCodeGenerator.h"

建立一個UITextFiled 用於輸入文字 建立一個生成二維碼的UiButton 建立一個UIImageView

UITextField *field;
UIButton *btn;
UIImageView *imgVV;

設定field的位置等

//文字框的位置
field = [[UITextField alloc]initWithFrame:CGRectMake((self.view.frame.size.width-200)/2, 100, 200, 44)];
	//提示文字
    field.placeholder = @"請輸入內容";
    field.borderStyle = UITextBorderStyleRoundedRect;
    //新增到檢視
    [self.view addSubview:field];

設定按鈕的位置等 記得新增一個點選方法

//按鈕的位置
btn = [[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width-200)/2, 180, 200, 44)];
	//為按鈕設定文字
    [btn setTitle:@"點選生成二維碼" forState:UIControlStateNormal];
    //為按鈕設定背景顏色
    btn.backgroundColor = [UIColor lightGrayColor];
    //給按鈕新增一個點選方法
    [btn addTarget:self action:@selector(abc) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

按鈕的點選方法內: 初始化ImageView 設定位置 設定二維碼 , 二維碼內容和生成 以及 把ImageView新增到檢視 (最好不要設定ImageView的背景顏色 , 如果設定了背景顏色 文字框內沒有內容的情況下 點選生成二維碼按鈕 , 就會出現一個ImageView純顏色 )

設定UIImageView的位置
imgVV = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width-200)/2, 300, 200, 200)];
	//為UIImageView設定二維碼圖片
    imgVV.image = [QRCodeGenerator qrImageForString:field.text imageSize:imgVV.bounds.size.width];
    //把圖片新增到檢視
    [self.view addSubview:imgVV];