swift跑马灯/滚动文字条

语言版本:swift4.2

工作中,很容易碰到跑马灯效果,网上的感觉都不怎么满意,就自己封装了个。

注意:一个时,会自动生成多个相同的循环播放

优点:支持autolayout布局、不仅限于label展示、宽度缓存处理、视图因需生成、视图缓存处理、用法简单和UItableView类似,可看demo

下载连接:https://github.com/wokua/LYHEntertainingDiversions-swift.git喜欢的话麻烦打个星支持下

OC版本

用法:

一 设置数据源:UIRunHouseViewDatasourse,设置space定义每个item间距,默认30

let runhouseView = UIRunHouseView()
runhouseView.dataSourse = self

二、注册重用cell

UIView的子类即可,如果需要在重用前处理cell内容,可以实现UIRunHouseItemProtocol协议,prepareForReuse方法里面处理就好

 runhouseView?.registerClasse(classType: CustomRunHouseView.classForCoder(), reuseIdentifier: "CustomRunHouseView")
        runhouseView?.registerClasse(classType: ImageTitleView.classForCoder(), reuseIdentifier: "ImageTitleView")

三、实现数据源方法:

 func numberOfItemsInRunHouseView(view:UIRunHouseView) -> Int;//一共多少个

  func runHouseView(runHouseView:UIRunHouseView,widthForIndex index:Int) -> CGFloat;//每个item宽度 ,内部已经实现缓存

   func runHouseView(runHouseView:UIRunHouseView,itemForIndex index:Int) -> UIView;//每个item的视图,因需生成,已经实现缓存

 func numberOfItemsInRunHouseView(view: UIRunHouseView) -> Int {
        return 3
    }
 func runHouseView(runHouseView: UIRunHouseView, itemForIndex index: Int) -> UIView {
        
        if index % 2 == 0 {
            var view = runHouseView.dequeneItemViewResueIdentity(resueIdentity: "CustomRunHouseView") as? CustomRunHouseView
            if view == nil {
                view = CustomRunHouseView()
            }
            view?.label.text = self.datas[index]
            return view!
        }else{
            var view = runHouseView.dequeneItemViewResueIdentity(resueIdentity: "ImageTitleView") as? ImageTitleView
            if view == nil {
                view = ImageTitleView()
            }
            view?.label.text = self.datas[index]
            return view!
        }
    }
    func runHouseView(runHouseView: UIRunHouseView, widthForIndex index: Int) -> CGFloat {
        let str = self.datas[index]
        let font = UIFont.systemFont(ofSize: 20)
        let rect = str.boundingRect(with:CGSize.init(width: CGFloat(MAXFLOAT), height: 50),options: NSStringDrawingOptions.usesLineFragmentOrigin,attributes: [NSAttributedString.Key.font:font],context:nil)
        if index % 2 == 0{
            return rect.size.width + 10
        }else{
            return rect.size.width + 50
        }
    }

四、reloaddata 刷新数据

你可能感兴趣的:(iOS,swift)