有段时间没有更新博客了,最近比较忙,今天和大家分享一个使用Swift实现的新特性功能吧

来源:互联网 发布:淘宝手机端用什么编辑 编辑:程序博客网 时间:2024/05/16 06:34

新特性是根据版本号判断是否需要显示的,现在很多的应用程序都有这个功能,主要是系统升级后,用户第一次进入系统时显示的功能,当然网络上不难找到很多第三方封装代码,但我们在使用第三方的时候还是要了解其工作原理的,我自己很直白的写了一份代码分享给大家,希望大家可以做个参考

功能分析:

1.使用继承自UICollectionViewController的类

2.UICollectionViewController必须设置布局和注册cell,这里我们默认使用流水布局,设置布局的大小和滚动方向(新特性一般为横向滚动,但系统默认为垂直滚动,需要设置),设置collectionView分页等属性(根据项目实际需求设置,这里我先只设置分页)同时设置数据源,遵守数据源协议并且实现数据源方法,这里先使用系统提供的cell

3.系统的cell不能满足我的项目需求,现在我要自定义一个cell,通过懒加载初始化图片和按钮控件并添加到视图中,在这里我使用纯代码设置控件的约束(当然也可以使用第三方的SnapKit进行设置,也很好用,这里我先使用系统提供的)

4.在初始化图片控件的时候可以对图片进行一张一张的赋值(这个对于我们程序员来说要崩溃的节奏啊),我们用稍微可以接受的方式,定义一个目标索引,图片的命名规范一般为后缀索引不同,我们可以通过拼接后缀的方式赋值,再通过索引判断显示的按钮是否要显示

5.因为刚刚我们使用的是系统cell,此时需要对2个地方进行更改,其一注册cell,其二创建cell,转换为我们自定义的cell

6.创建一个通知并通过通知来改变window的根控制器


小伙伴们,我使用的是Swift语言哦!下面直接上代码:


//MARK:创建视图private let reuseIdentifier = "Cell"class SinaNewFeatuerViewController: UICollectionViewController {    let layout = UICollectionViewFlowLayout()    //1.在初始化方法中设置布局   required init(){        super.init(collectionViewLayout: layout)    }    required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }    override func viewDidLoad() {        super.viewDidLoad()        setUpUI()       }    func setUpUI(){        //2.注册cell        self.collectionView!.registerClass(SinaNewFeatuerCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)        //设置分页        collectionView?.pagingEnabled = true        //去掉分页线        collectionView?.bounces = false                //设置ITEM的大小,所有的item都在布局上面        layout.itemSize = UIScreen.mainScreen().bounds.size        //设置横向滚动和间距        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal        layout.minimumInteritemSpacing = 0        layout.minimumLineSpacing = 0    }    // MARK: UICollectionViewDataSource实现数据源方法//分组    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {        // #warning Incomplete implementation, return the number of sections        return 1    }//每组多少行    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        // #warning Incomplete implementation, return the number of items        return 4    }//返回怎样的cell    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SinaNewFeatuerCollectionViewCell    //设置cell的背景颜色        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.yellowColor() : UIColor.redColor()       //给cell赋值        cell.index = indexPath.item                return cell    }}//MARK:自定义cellclass SinaNewFeatuerCollectionViewCell: UICollectionViewCell {    //定义新特性界面的索引图片    var index:Int = 0 {        didSet{            pictuer.image = UIImage(named: "new_feature_\(index + 1)")            if index == 3 {                enterBtn.hidden = false            }else{                enterBtn.hidden = true            }        }    }    override init(frame: CGRect) {        super.init(frame: frame)        addSub()    }    required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }    //添加子控件    func addSub(){       addSubview(pictuer)       addSubview(enterBtn)                //设置图片位置        pictuer.frame = UIScreen.mainScreen().bounds        enterBtn.translatesAutoresizingMaskIntoConstraints = false                //手动添加约束,添加到cell               addConstraint(NSLayoutConstraint(item: enterBtn, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0))       addConstraint(NSLayoutConstraint(item: enterBtn, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: -100))    }            //3.懒加载图片    lazy var pictuer:UIImageView = {        let pic = UIImageView()        return pic    }()       //懒加载按钮    lazy var enterBtn:UIButton = {        let bt = UIButton()        bt.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: .Normal)        bt.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: .Highlighted)        bt.setTitle("开始体验", forState:.Normal)        bt.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)        bt.sizeToFit();        //给按钮添加点击事件        bt.addTarget(self, action: "didSelectClick", forControlEvents: .TouchUpInside)        return bt    }()    func didSelectClick(){        printLog("点击了开始体验吧")        //新特性        NSNotificationCenter.defaultCenter().postNotificationName(notification, object: nil)    }}//MARK:APPDelegate设置根控制器//设置根控制器          window?.rootViewController = (SinaAoccountViewController.shareInsatance.isLog) ? (isNewFeatuer()) : (SinaBaseTabBarController()) //注册一个通知        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeView:", name: notification, object: nil)        return true    }//在登录的情况下,判断是否有新特性    func isNewFeatuer()->UIViewController{        return getVision() ? SinaNewFeatuerViewController() : SinaWelcomViewController()    }    //拿到版本    func getVision()->Bool{        let vs = "vision"        //读取旧版本        let oldVision = NSUserDefaults.standardUserDefaults().objectForKey(vs) as? String        //记录当前新版本        let newVision = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String        //保存新版本        NSUserDefaults.standardUserDefaults().setObject(newVision, forKey: vs)        //对2个版本进行比较        if let old = oldVision {            if newVision.compare(old) == NSComparisonResult.OrderedDescending {                return true            }else{                return false            }        }        //没有旧版本        return true    }    func changeView(not:NSNotification){       //根据通知判断当前要显示的界面        if not.object == nil {            window?.rootViewController = SinaBaseTabBarController()//                SinaBaseTabBarController()//                SinaWelcomViewController()        }else{            window?.rootViewController = SinaWelcomViewController()//                SinaNewFeatuerViewController()        }    }    //良好的编程习惯要移除观察者    deinit{        removeObserver(self, forKeyPath: notification)    }


0 0
原创粉丝点击