你的位置:首页 > 操作系统

[操作系统]Swift动态添加UIImageView并添加事件


Swift动态添加UIImageView并添加事件:

1. 创建UIImageView实例,并进行初始化

2. 设置UIImageView的用户交互属性userInteractionEnabled为True

3. 添加手势识别事件

4. 实现事件

//获取屏幕的尺寸    print(UIScreen.mainScreen().bounds)    //获取屏幕应用程序尺寸(不包括状态栏)    print(UIScreen.mainScreen().applicationFrame)        //定义UIImageView集    var data:[(String,[Int])]=[      ("0.png",[30,80,100,150]),      ("half.png",[160,80,100,150]),      ("1.png",[290,80,100,150]),      ("2.png",[30,260,100,150]),      ("3.png",[160,260,100,150]),      ("5.png",[290,260,100,150]),      ("8.png",[30,440,100,150]),      ("13.png",[160,440,100,150]),      ("infinitegreatness.png",[290,440,100,150])    ]    
    //动态添加UIImageView for i in 0..<data.count{ let (name,rect) = data[i] let image:UIImageView = UIImageView.init(frame: CGRect(x: rect[0], y: rect[1], width: rect[2], height: rect[3])) image.image = UIImage(named: name)
        //Enable用户交互 image.userInteractionEnabled = true
        //添加手势识别 image.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "touchSelect:")) self.view.addSubview(image) }

func touchSelect(sender: UITapGestureRecognizer)->Void{        let newImage:UIImageView = UIImageView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))    newImage.image = UIImage(named: "1.png")    self.view.addSubview(newImage)  }