[英]Listen to LongPressGesture on UITabBarItem
我想在單個UITabBarItem上附加一個簡單的long press
。 swift 4
可能嗎? 我已經嘗試過如下操作,但是UITabBarItem沒有可以實現的事件成員
uiTabBar
是出口。 我也看到我可以使用UITabBarDelegate,但是我沒有使用它。 longTap函數的簽名如下所示:
@objc func longTap(_ sender: UIGestureRecognizer){}
我最終將UIButton
放在要附加UILongPressGestureRecognizer
的UITabBarItem
UILongPressGestureRecognizer
。 我使用以下功能准備了按鈕:
//Declare the button
let uiTabBar = UIButton(frame: CGRect.zero)
func setupMiddleButton() {
// Create image
let africaIcon = UIImage(named: "ic_africa")
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
uiTabBar.frame = CGRect(x: 0, y: 0, width: tabBarItemSize.width, height: tabBar.frame.size.height)
var menuButtonFrame = uiTabBar.frame
menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height - self.view.safeAreaInsets.bottom
menuButtonFrame.origin.x = self.view.bounds.width/2 - menuButtonFrame.size.width/2
uiTabBar.frame = menuButtonFrame
uiTabBar.setImage(africaIcon, for: UIControlState.normal)
//uiTabBar.backgroundColor = UIColor.green
self.view.addSubview(uiTabBar)
self.view.layoutIfNeeded()
}
為了附加事件,我做了以下工作:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap(_:)))
tapGesture.numberOfTapsRequired = 1
uiTabBar.addGestureRecognizer(tapGesture)
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
uiTabBar.addGestureRecognizer(longGesture)
//Set default tab
self.selectedIndex = 1;
選擇器方法如下所示:
@objc func normalTap(_ sender: UIGestureRecognizer){
self.selectedIndex = 1;
}
@objc func longTap(_ sender: UIGestureRecognizer){
print("Long tap")
if sender.state == .ended {
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
//This is when the long event is triggered
}
else if sender.state == .began {
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.