swift 跑马灯(50行代码完美实现,超简单)

Posted ihoudf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 跑马灯(50行代码完美实现,超简单)相关的知识,希望对你有一定的参考价值。

1、(10行)创建一个跑马灯背景

    let BG = UIView()
    BG.layer.cornerRadius = 6
    BG.backgroundColor = .black.withAlphaComponent(0.4)
    self.view.addSubview(BG)
    BG.snp.makeConstraints  make in
        make.left.equalTo(20)
        make.width.equalTo(300)
        make.top.equalTo(200)
        make.height.equalTo(50)
    

2、(8行)为第三步创建一个隐藏的父view,clipsToBounds = true是关键,可以让文字不超出去。

    let announceBG = UIView()
    announceBG.clipsToBounds = true
    BG.addSubview(announceBG)
    announceBG.snp.makeConstraints  make in
        make.left.equalTo(40)
        make.right.equalTo(-10)
        make.top.bottom.equalTo(0)
    

3、(8行)创建一个label,用来显示文字并滚动。布局的make.left.equalTo(announceBG.snp.right)是关键,让label在父视图的右侧开始。

    let announceL = UILabel()   
    announceL.textColor = .white
   announceL.font = .systemFont(ofSize: 18)
   announceBG.addSubview(announceL)
   announceL.snp.makeConstraints  make in
       make.top.bottom.equalToSuperview()
       make.left.equalTo(announceBG.snp.right)
   

4、(26行)动画

 func showScrollAnimation(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: 18), size: .zero)
        let announceBgW = kScreenWidth - 56 - 21
        
        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")
    
    
    // 计算字符串长度
    func sizeWithText(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
    

5、大功告成。求打赏、点赞、关注、收藏。

以上是关于swift 跑马灯(50行代码完美实现,超简单)的主要内容,如果未能解决你的问题,请参考以下文章

swift 跑马灯(50行代码完美实现,超简单)

OC Swift 走马灯效果

MATLAB 50行代码绘制超好看的旋转九边形

android ViewPager实现 跑马灯切换图片+多种切换动画

pygame实现简单的金币旋转效果,不到50行代码哦!

pygame实现简单的金币旋转效果,不到50行代码哦!