1. 程式人生 > >Swift-如何自定義鍵盤(iOS)

Swift-如何自定義鍵盤(iOS)

//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 in0..<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) {

//在此處做響應的處理

    }