我有TabBar控制器,上面添加了3个ViewController。现在,当我们点击特定选项卡时,所有选项卡都正常切换。我想要,从左到右或从左到右滑动TabBar的功能相同。 所以请给我一些建议。 我怎么能这样做?
答案 0 :(得分:1)
您可以将UISwipeGestureRecognizer
添加到UITabBar
通过根据手势方向设置来处理滑动手势
- (void)viewDidLoad {
[super viewDidLoad];
UISwipeGestureRecognizer *leftToRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftToRightSwipeDidFire)];
leftToRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
[self.tabBarController.tabBar addGestureRecognizer:leftToRightGesture];
UISwipeGestureRecognizer *rightToLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightToLeftSwipeDidFire)];
rightToLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
[self.tabBarController.tabBar addGestureRecognizer:rightToLeftGesture];
}
- (void)leftToRightSwipeDidFire {
UITabBar *tabBar = self.tabBarController.tabBar;
NSInteger index = [tabBar.items indexOfObject:tabBar.selectedItem];
if (index > 0) {
self.tabBarController.selectedIndex = index - 1;
} else {
return;
}
}
- (void)rightToLeftSwipeDidFire {
UITabBar *tabBar = self.tabBarController.tabBar;
NSInteger index = [tabBar.items indexOfObject:tabBar.selectedItem];
if (index < tabBar.items.count - 1) {
self.tabBarController.selectedIndex = index + 1;
} else {
return;
}
}
答案 1 :(得分:1)
为每个视图控制器的视图添加2(一个用于左侧,另一个用于右侧)滑动手势并进行IBAction
- (IBAction)swipeRightAction:(UIGestureRecognizer *)sender {
UISwipeGestureRecognizerDirection directions=[(UISwipeGestureRecognizer *)sender direction];
switch (directions) {
case UISwipeGestureRecognizerDirectionRight:
indexNumberItem--;
break;
case UISwipeGestureRecognizerDirectionLeft:
indexNumberItem++;
break;
default:
break;
}
if (indexNumberItem<3) {
indexNumberItem=0;
}
if (indexNumberItem>=3) {
indexNumberItem=2;
}
self.tabBarController.selectedViewController= [self.tabBarController.viewControllers objectAtIndex:indexNumberItem];
}
答案 2 :(得分:0)
您的所有子ViewControllers都可以从一个为您完成所有繁重任务的类继承。
我就是这样做的
class SwipableTabVC : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let left = UISwipeGestureRecognizer(target: self, action: #selector(swipeLeft))
left.direction = .left
self.view.addGestureRecognizer(left)
let right = UISwipeGestureRecognizer(target: self, action: #selector(swipeRight))
right.direction = .right
self.view.addGestureRecognizer(right)
}
func swipeLeft() {
let total = self.tabBarController!.viewControllers!.count - 1
tabBarController!.selectedIndex = min(total, tabBarController!.selectedIndex + 1)
}
func swipeRight() {
tabBarController!.selectedIndex = max(0, tabBarController!.selectedIndex - 1)
}
}
现在,属于UITabBarController的所有viewcontroller都可以从SwipableTabVC
而不是UIViewController继承。