CALayer 判断是否点击hitTest
CALayer并不关心任何响应链事件,所以不能直接处理触摸事件或者手势。但是它有一系列的方法帮你处理事件:containsPoint:
和hitTest:
。
下来看看这两个方法怎么使用 。
首先来看containsPoint
, 首先在界面上拖一个UIView出来 , 在上面放两份layer 。
ly1.frame = CGRectMake(0,0,20,20)
ly1.backgroundColor = UIColor.redColor().CGColor
v1.layer.addSublayer(ly1)
ly2.frame = CGRectMake(40,20)
ly2.backgroundColor = UIColor.redColor().CGColor
v1.layer.addSublayer(ly2)
大概就这样的
然后重写touchesBegan
方法
override func touchesBegan(touches: Set<UITouch>,withEvent event: UIEvent?) {
var p = (touches as NSSet).anyObject()?.locationInView(v1);
p = v1.layer.convertPoint(p!,fromLayer: v1.layer)
//方法1
if v1.layer.containsPoint(p!) {
p = ly1.convertPoint(p!,fromLayer: v1.layer)
if ly1.containsPoint(p!){
let alert = UIAlertView(title: "点击了",message: "第一个被点击了",delegate: nil,cancelButtonTitle: "OK")
alert.show()
}
p = ly2.convertPoint(p!,fromLayer: v1.layer)
if ly2.containsPoint(p!){
let alert = UIAlertView(title: "点击了",message: "第二个被点击了",cancelButtonTitle: "OK")
alert.show()
}
}
}
效果:
就这样的效果 , 别的Layer 可以暂时不管
hitTest
方法
//方法2
let p1 = (touches as NSSet).anyObject()?.locationInView(self.v1);
//p1 = v1.layer.convertPoint(p1!,fromLayer: v1.layer)
let clickLayer = ly3.hitTest(p1!)
print(ly3.frame)
if(clickLayer == ly3){
let alert = UIAlertView(title: "点击了",message: "第三个被点击了",delegate: nil,cancelButtonTitle: "OK")
alert.show()
}
let anoLayer = ly4.hitTest(p1!)
if(anoLayer == ly4){
let alert = UIAlertView(title: "点击了",message: "点击了小鸟",cancelButtonTitle: "OK")
alert.show()
}
这个方法方便多了,代码量少多了 , 以后就用这个了。。。
看看效果
contensRect
前面讲过者个属性是用来裁剪图片的 , 用一个示例来看看这个属性的用法
这个图
先在界面上拖写view
拖到控制器
@IBOutlet var digitViews: [UIView]!
一个数组 。
img = UIImage(named: "sz")!
for item in digitViews{
item.layer.contents = UIImage(named: "sz")!.CGImage
item.layer.contentsRect = CGRectMake(0,0.1,1.0);
item.layer.contentsGravity = kCAGravityResizeAspect;
}
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self,selector: "showTime",userInfo: nil,repeats: true)
timer.fire()
func showTime(){
let calendar = NSCalendar.currentCalendar()
// let unitFlags =
let comp = calendar.components(NSCalendarUnit.Second,fromDate: NSDate())
setDigit(comp.second%10,ly: digitViews[0])
setDigit(comp.second/10,ly: digitViews[1])
let comp1 = calendar.components(NSCalendarUnit.Minute,fromDate: NSDate())
setDigit(comp1.minute%10,ly: digitViews[2])
setDigit(comp1.minute/10,ly: digitViews[3])
let comp2 = calendar.components(NSCalendarUnit.Hour,fromDate: NSDate())
setDigit(comp2.hour%10,ly: digitViews[4])
setDigit(comp2.hour/10,ly: digitViews[5])
}
func setDigit(t:Int,ly:UIView){
ly.layer.contentsRect = CGRectMake(0.1*CGFloat(t),1);
}
效果大家也看到了 , 就是上面图下面的那个电子表