最简单实现侧边栏的方法----UISplitViewController

来源:互联网 发布:淘宝商家货到付款 编辑:程序博客网 时间:2024/06/06 00:15

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:


0 0
原创粉丝点击