天天看點

Objective-C-如何自定義鍵盤(iOS)

//createMyInputView該方法傳回一個UIImageView類型的視圖

    UIImageView *myView= [self createMyInputView];

    //讓此視圖作為鍵盤的背景視圖

    textField.inputView = myView;

    //添加附件區域

    UIView *upView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];

    //附件區域的顔色

    upView.backgroundColor=[UIColor grayColor];

    //讓upView作為附件區域

    textField.inputAccessoryView = upView;

    //在附件區域中添加“确定”按鈕

    UIButton *sendButton=[UIButton buttonWithType:UIButtonTypeSystem];

    sendButton.frame=CGRectMake(self.view.frame.size.width-80, 6, 80, 40);

    [sendButton setTitle:@"确定" forState:UIControlStateNormal];

    [upView addSubview:sendButton];

//自定義鍵盤

-(UIImageView *)createMyInputView{

    //建立一個背景ImageView

    UIImageView *inputView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];

    //添加背景圖檔

    inputView.image = [UIImage imageNamed:@"DOVE 1"];

    //打開使用者互動

    inputView.userInteractionEnabled = YES;

    //視圖的背景色

    inputView.backgroundColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];

    //添加按鈕

    NSArray *titleArray=@[@"京",@"津",@"追",@"夢",@"人",@"自",@"定",@"義",@"鍵",@"盤",@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"十",@"取錢",@"紅包",@"收"];

    //有多少個字就建立多少個按鈕

    for(int i = 0; i< titleArray.count; i++)

    {

        //建立按鈕

        UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];

        //按鈕的坐标

        button.frame=CGRectMake(40*(i%10), i/10*40, 40, 40);

        //按鈕上顯示的文字

        [button setTitle:titleArray[i] forState:UIControlStateNormal];

        //把建立的每一個按鈕添加到inputView上

        [inputView addSubview:button];

        //設定按鈕的tag值

        button.tag = i+1;

        //給每個按鈕添加點選事件

        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    }

    //傳回背景視圖

    return inputView;

}

//按鈕的點選事件

-(void)btnClick:(UIButton *)button

{

    //在此處做響應的處理

}