简单:swift 实现文本横向滚动,跑马灯效果

1.首先放三个控件

         headView.addSubview(BG)//可以滚动的视图bg

        BG.addSubview(announceBG)//具体消息内容的bg 必须要有这个 不然消息显示会超出范围

        announceBG.addSubview(announceL)//具体消息内容

 

        BG.snp.makeConstraints { make in

            make.left.equalTo(messageImageV.snp.right).offset(8.point)

            make.top.equalTo(bannerView.snp.bottom).offset(16.point)

            make.right.equalToSuperview().offset(-45.point)

            make.height.equalTo(23.point)

        }

 

        announceBG.snp.makeConstraints { make in

            make.left.equalTo(1.point)

            make.right.equalTo(-1.point)

            make.top.bottom.equalTo(0)

        }

 

        announceL.snp.makeConstraints { make in

            make.top.bottom.equalToSuperview()

            make.left.equalTo(announceBG.snp.right)

        }

 

 

    //MARK: ---- 以下三个控件第二种显示消息跑马灯效果

    //显示消息内容的label

    lazy var announceL: UILabel = {

        let view = UILabel()

        view.text = ""

        view.textColor = .hexColor("#FFFFFF")

        view.textAlignment = .left

        view.font = .font(size: 12, alias: .pfMedium)

        return view

    }()

    

    lazy var BG: UIView = {

        let view = UIView()

        return view

    }()

    

    lazy var announceBG: UIView = {

        let view = UIView()

        view.clipsToBounds = true

        return view

    }()

 

 

2.具体实现方法

    funcshowScrollAnimation(content: String) {

           // 如果没有内容移除动画,并隐藏

//           if content.removeAllSapce.count <= 0 {

//               announceL.layer.removeAllAnimations()

//               self.isHidden = true

//               return

//           }

           

           // 根据文字长度计算一个时间

//          self.isHidden = false

        self.announceL.text = content

        var duration = CGFloat(content.count)/4.0

        

        //字符串宽度

        let charW = sizeWithText(text: content, font: .systemFont(ofSize: 12), size: .zero)

        let announceBgW = UIScreen.width - 95.point

        

        if charW < announceBgW + 30 {

            duration = 7

        }

        

        // 动画

        let anim = CABasicAnimation()

        anim.toValue = -announceBgW-charW

        anim.duration = duration

        anim.repeatCount = MAXFLOAT

        anim.isRemovedOnCompletion = false

        announceL.layer.add(anim, forKey: "transform.translation.x")

    }

       

    // 计算字符串长度

    funcsizeWithText(text: String, font: UIFont, size: CGSize) -> CGFloat {

        let attributes = [NSAttributedString.Key.font: font]

        let option = NSStringDrawingOptions.usesLineFragmentOrigin

        let width = text.boundingRect(with: size, options: option, attributes: attributes, context: nil).size.width

        return width

    }

 

 

3.调用

    self.showScrollAnimation(content: setMessage)

 

posted on 2022-07-11 18:26  yucaijiang  阅读(538)  评论(0编辑  收藏  举报

导航