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

Swift-如何自定义键盘(iOS)

2016-09-21 13:46 211 查看
//createMyInputView该方法返回一个UIImageView类型的视图

        let myView =
createMyInputView();

       
//让此视图作为键盘的背景视图

        textField.inputView = myView

        

        //添加附件区域

        let upView =
UIView.init(frame:
CGRectMake(0,
0, self.view.frame.size.width,
60))

        //附件区域的颜色

        upView.backgroundColor =
UIColor.grayColor()

        //让upView作为附件区域

        textField.inputAccessoryView = upView

        

        //在附件区域中添加“确定”按钮

        let sendButton =
UIButton.init(type:
UIButtonType.System)

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

        sendButton.setTitle("确定",
forState: UIControlState.Normal)

        upView.addSubview(sendButton)

//自定义键盘

    func createMyInputView() ->
UIImageView {

        

        //创建一个背景ImageView

        let inputView =
UIImageView.init(frame:
CGRectMake(0,
0, self.view.frame.size.width,
200))

        //添加背景图片

        inputView.image =
UIImage(named:"DOVE 1")

        //打开用户交互

        inputView.userInteractionEnabled =
true

        //视图的背景色

        inputView.backgroundColor =
UIColor.init(white:
1, alpha: 0.5)

        

        //添加按钮

        let titleArray = ["京","津","追","梦","人","自","定","义","键","盘","一","二","三","四","五","六","七","八","九","十","取钱","红包","收"]

        

       
//有多少个字就创建多少个按钮

        for i
in 0..<titleArray.count {

            

            //创建按钮

            let button =
UIButton.init(type:
UIButtonType.System)

            //按钮的坐标

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

            //按钮上显示的文字

            button.setTitle(titleArray[i], forState:
UIControlState.Normal)

            //把创建的每一个按钮添加到inputView上

            inputView.addSubview(button)

            //设置按钮的tag值

            button.tag = i+1

            //给每个按钮添加点击事件

            button.addTarget(self, action:
#selector(btnClick(_:)), forControlEvents:
UIControlEvents.TouchUpInside)

        }

        

        //返回背景视图

        return inputView;

    }

    

   
//按钮的点击事件

    func btnClick(button:UIButton) {

        

        //在此处做响应的处理

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