Demo下载地址
1.创建一个新的工程,在storyboard里面删除已有的viewController,拖入一个UISplitviewControloler.
2.删除Navigation view,建立splitviewController 与 TableViewControl之间的联系,选择 master viewController,
3.将tableview的content修改成static,添加多个cell
4.添加多个UIViewController,并和cell建立关联。
5.实现UISplitViewController的子类,指定侧边栏的宽度,取消手势事件:
override func viewDidLoad() {
self.preferredPrimaryColumnWidthFraction =0.2
self.presentsWithGesture =false;
}
将storyboard中的splitViewController的关联类修改成实现的UISpliteViewController的子类
6.给添加的detail ViewController 添加实现类,
class ViewController: UIViewController {
overridefunc viewDidLoad() {
super.viewDidLoad()
//添加menu button
var btnShow = UIButton(frame: CGRectMake(10,20,100,30));
btnShow.setTitle("Menu",forState:UIControlState.Normal);
btnShow.addTarget(self,action:"showMenu:",forControlEvents: UIControlEvents.TouchUpInside);
btnShow.backgroundColor = UIColor.grayColor();
self.view.addSubview(btnShow);
}
// button event
func showMenu(sender:UIButton){
//animation when change sideBar
UIView.animateWithDuration(0.5,animations: {() in
if self.splitViewController!.preferredDisplayMode == UISplitViewControllerDisplayMode.AllVisible{
//hide sideBar
self.splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.PrimaryHidden;
}else{
//show sideBar
self.splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible;
}
})
}
overridefunc touchesEnded(touches:Set<NSObject>,withEvent event:UIEvent) {
//hide sideBar when tap detailViewController
UIView.animateWithDuration(0.5,animations: {() in
if self.splitViewController!.preferredDisplayMode == UISplitViewControllerDisplayMode.AllVisible{
self.splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.PrimaryHidden;
}
})
}
}
OK,简单的侧边栏实现了:
可以根据实际需要设置侧边来是ovelay 还是sidebyside:
原文链接:https://www.f2er.com/swift/327076.html