有人可以帮我在icarousel中为中心图像添加双击识别器吗?在下面的快速代码中,您可以看到识别器已编程,但它会在屏幕上的任何位置作出反应,而不仅仅是在中心图像上。我想我必须将手势连接到newView但我尝试了几件事,但没有解决问题。在Objective-C中有很多例子,但是Swift很难在论坛上找到解决方案。希望有人能告诉我如何正确编码。
import UIKit
let image0 = UIImage(named: "Afrojack")
let image1 = UIImage(named: "Calvin Harris")
let image2 = UIImage(named: "Martin Garrix")
var imageArray = [image0, image1, image2]
class ViewController: UIViewController, iCarouselDataSource, iCarouselDelegate
{
var items: [Int] = []
@IBOutlet weak var carousel: iCarousel!
override func awakeFromNib()
{
super.awakeFromNib()
for i in 0...2
{
items.append(i)
}
}
override func viewDidLoad()
{
super.viewDidLoad()
carousel.type = .CoverFlow2
}
//show message when screen is tapped twice
func message(){
let alertView = UIAlertView(title: "Oops!", message: "Something happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
}
func numberOfItemsInCarousel(carousel: iCarousel!) -> Int
{
return items.count
}
@objc func carousel(carousel: iCarousel!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! {
var newView = view
var label: UILabel! = nil
if newView == nil {
//create new view
//don't do anything specific to the index within
//this `if (view == nil) {...}` statement because the view will be
//recycled and used with other index values later
newView = UIImageView(frame:CGRectMake(0, 0, 200, 200))
//(newView as! UIImageView).image = UIImage(named: "page")
newView.contentMode = .Center
// set label properties
label = UILabel(frame:newView.bounds)
label.backgroundColor = UIColor.clearColor()
label.textAlignment = .Center
label.font = label.font.fontWithSize(50)
label.tag = 1
newView.addSubview(label)
}
else
{
//get a reference to the label in the recycled view
label = newView.viewWithTag(1) as! UILabel!
}
//set item label
//remember to always set any properties of your carousel item
//views outside of the `if (view == nil) {...}` check otherwise
//you'll get weird issues with carousel item content appearing
//in the wrong place in the carousel
//label.text = "\(items[index])"
(newView as! UIImageView).image = imageArray[items[index]]
newView.userInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self , action: "message")
tapGesture.numberOfTapsRequired = 2
newView.addGestureRecognizer(tapGesture)
return newView
}
}
func carousel(carousel: iCarousel!, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat
{
if (option == .Spacing)
{
return value * 1.1
}
return value
}
答案 0 :(得分:1)
您是否尝试将此代码置于newView
初始化之下?
let tapGesture = UITapGestureRecognizer(target: self , action: "message")
tapGesture.numberOfTapsRequired = 2
newView.addGestureRecognizer(tapGesture)
您还应该在viewDidLoad()
。
修改强>
你应该在 newView
之后将识别器设置为100%而不是nil,原因是现在,newView
可以是nil
(你有{ {1}})
所以放在所有if newView == nil
语句下面。它应该工作。