我正在我的项目中使用TGLParallaxCarousel库构建一个引用应用程序。我尝试在其上添加两个CustomView
(favButton和shareButton)来自定义TGLParallaxCarouselItem
UIButton
。
screenshot to the quote cards (CustomView) I create
我能够根据其状态更改UIButton视图 - 无论当前引用是否有效,通过这样做:
convenience init(frame: CGRect, number: Int) {
self.init(frame: frame)
currentQuote = quoteData[number]
favButton.tag = number
currentQuote.faved == true ? favButton.setImage(#imageLiteral(resourceName: "fav-on"), for: .normal) : favButton.setImage(#imageLiteral(resourceName: "fav-off"), for: .normal)
}
但是我需要通过单击favButton来打开和关闭fav。我尝试将favButton作为IBAction
直接连接到XIB
文件,尝试addAction
运行,但我仍然无法访问favButton点击状态。
请帮忙。我该怎么办?
更新
我在favButton上试过addTarget
。它不起作用。我的点击被检测为点击CustomView而不是特别是favButton。
这里是我点击CustomView上任意位置时触发的detectTap
函数(包括在favButton上)。此函数位于TGLParallaxCarousel.swift
func detectTap(_ recognizer:UITapGestureRecognizer) {
let targetPoint: CGPoint = recognizer.location(in: recognizer.view)
currentTargetLayer = mainView.layer.hitTest(targetPoint)!
guard let targetItem = findItemOnScreen() else { return }
let firstItemOffset = (items.first?.xDisp ?? 0) - targetItem.xDisp
let tappedIndex = -Int(round(firstItemOffset / xDisplacement))
self.delegate?.carouselView(self, didSelectItemAtIndex: tappedIndex)
if targetItem.xDisp == 0 {
self.delegate?.carouselView(self, didSelectItemAtIndex: tappedIndex)
}
else {
selectedIndex = tappedIndex
}
}
答案 0 :(得分:0)
您是否尝试使用addTarget
?
convenience init(frame: CGRect, number: Int) {
self.init(frame: frame)
currentQuote = quoteData[number]
favButton.tag = number
currentQuote.faved == true ? favButton.setImage(#imageLiteral(resourceName: "fav-on"), for: .normal) : favButton.setImage(#imageLiteral(resourceName: "fav-off"), for: .normal)
favButton.addTarget(self, action: #selector(toggle), for: .touchUpInside)
}
@objc fileprivate func toggle() {
currentQuote.faved = !currentQuote.faved
currentQuote.faved == true ? favButton.setImage(#imageLiteral(resourceName: "fav-on"), for: .normal) : favButton.setImage(#imageLiteral(resourceName: "fav-off"), for: .normal)
}