前端之家收集整理的这篇文章主要介绍了
跑马灯动画点击事件,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//
// SNMarqueeView.swift
// Futianwisdom
//
// Created by Snow on 16/5/23.
// Copyright (c) 2016年 futianwisdom. All rights reserved.
//
import UIKit
import SwiftyJSON
protocol SNMarqueeViewDelegate {
func didSelectURL(url: String)
}
class SNMarqueeView: UIView {
var delegate: SNMarqueeViewDelegate?
private var marqueeTitle = ""
private var titleArray = [String]()
private var urlArray = [String]()
private var mark:CGRect!
private var lastLabelFrame = CGRectZero
private var labArr = [UILabel]()
private var isStop = false
private var timeInterval1: NSTimeInterval!
convenience init(frame: CGRect,json: [JSON]) {
self.init(frame: frame)
for obj in json {
marqueeTitle += obj["title"].stringValue
titleArray.append(obj["title"].stringValue)
urlArray.append(obj["link"].stringValue)
}
self.backgroundColor = UIColor.whiteColor()
self.clipsToBounds = true
let tapGesture = UITapGestureRecognizer(target: self,action: "tapClick:")
self.addGestureRecognizer(tapGesture)
timeInterval1 = NSTimeInterval(marqueeTitle.characters.count/2)
for _ in 0...1 {
for title in titleArray {
let lab = UILabel()
lab.frame = CGRectZero
lab.textColor = UIColor.grayColor()
lab.font = UIFont.boldSystemFontOfSize(14.0)
lab.text = title
lab.userInteractionEnabled = false
//计算textLab的大小
let sizeOfText = lab.sizeThatFits(CGSizeZero)
lab.frame = CGRectMake(
lastLabelFrame.origin.x + lastLabelFrame.size.width,0,sizeOfText.width,self.bounds.size.height)
lastLabelFrame = lab.frame
self.addSubview(lab)
labArr.append(lab)
}
}
mark = CGRectMake(0,lastLabelFrame.origin.x + lastLabelFrame.size.width,self.bounds.size.height)
self.labAnimation()
}
//跑马灯动画
func labAnimation() {
if (!isStop) {
UIView.transitionWithView(self,duration: timeInterval1,options: UIViewAnimationOptions.CurveLinear,animations: {
for label in self.labArr {
label.frame.origin.x -= self.mark.size.width/2
}
},completion: { finished in
for label in self.labArr {
label.frame.origin.x += self.mark.size.width/2
}
self.labAnimation()
})
} else {
self.layer.removeAllAnimations()
}
}
func start() {
isStop = false
self.labAnimation()
}
func stop() {
isStop = true
self.labAnimation()
}
func tapClick(gesture: UITapGestureRecognizer) {
let clickPoint = gesture.locationInView(self)
for view in self.subviews {
if let label = view as? UILabel {
if let obj = label.layer.presentationLayer() as? CALayer {
if (obj.hitTest(clickPoint) != nil) {
if let text = label.text {
for (index,value) in EnumerateSequence(titleArray) {
if text == value {
if urlArray.count > index {
self.delegate?.didSelectURL(urlArray[index])
}
}
}
}
}
}
}
}
}
}