iOS11开发教程(二十三)iOS11应用视图实现按钮的响应(3)

iOS11开发教程(二十三)iOS11应用视图实现按钮的响应(3)

2.使用代码添加按钮实现的响应

使用代码添加的按钮,实现响应需要使用到addTarget(_:action:for:)方法,其语法形式如下:

func addTarget(_ target: AnyObject?, action: Selector, for controlEvents: UIControlEvents)

其中,参数说明如下:

target:表示目标对象。它是动作消息的发送方。

action:表示选择器,用来识别动作消息。它不可以为空。

controlEvents:表示控件事件。在iOS中有19种控件事件,如表2-4所示。

表2-4 控件事件

【示例2-5】以下将实现轻拍按钮,改变主视图背景颜色的功能。代码如下:

import UIKit

class ViewController: UIViewController {

    var isCyan:Bool=false

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        let button=UIButton(frame: CGRect(x: 90, y: 545, width: 225, height: 30))

        button.setTitle("Tap me,Change View Color", for: UIControlState())                       //设置按钮的标题

        button.setTitleColor (UIColor.black, for: UIControlState())                                         //设置按钮标题的颜

        self.view.addSubview(button)

  button.addTarget(self, action: #selector(ViewController.tapbutton), for: UIControlEvents.touchUpInside)

    }

    @objc func tapbutton(){

        if(isCyan){

            self.view.backgroundColor=UIColor.white

            isCyan=false

        }else{

            self.view.backgroundColor=UIColor.cyan

            isCyan=true

        }

    }

……

}

此时运行程序,首先会看到如图2.14的效果。当轻拍Tap me,Change View Color按钮后,主视图的背景变为青色,如图2.15所示。当再一次轻拍Tap me,Change View Color按钮,主视图的背景颜色将会变回原来的白色。

图2.14 运行效果 图2.15 运行效果

你可能感兴趣的:(iOS11开发教程(二十三)iOS11应用视图实现按钮的响应(3))