我在项目中使用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上的任意位置(包括favButton)点击时触发的
detectTap
函数。此函数在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
}
}
最佳答案
您是否尝试使用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)
}
关于ios - 从UIButton触发操作,单击自定义XIB,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49193295/