ios - 通过删除和添加字母对 UILabel 产生选取框效果 - Swift 3

标签 ios swift xcode swift3 marquee

谁能解释一下如何在 Swift 3.0 中实现这种效果?这几乎是一个字幕效果,但我不想滑动 UILabel。

如果能这样就好了

enter image description here

删除第一个字母并添加第 20 个字母,然后删除第二个字母并添加 21 等等,直到字符串中文本的末尾。我是一个菜鸟,我什至不知道如何开始。

最佳答案

听起来像是一个有趣的练习,所以这是我的看法:

Please note that is by no means production-ready code, but rather a quick demonstration of the idea behind this. Also the snippet below is written in the context of a playground in order to test things quickly.

import UIKit
import PlaygroundSupport

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 120, height: 30))
let text  = "marquee effect on UILabel by removing letters in front and adding in end in swift 3"
label.lineBreakMode   = .byClipping
label.text            = text
label.backgroundColor = .white
label.textAlignment   = .left

let timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { _ in
    DispatchQueue.main.async {
        if let text = label.text, !text.isEmpty {
            let index = text.index(after: text.startIndex)
            label.text = label.text?.substring(from: index)
        }
    }
}

PlaygroundPage.current.liveView = label

这是什么让你:

enter image description here


一些注意事项:

  1. 您可以使用一些其他机制来代替计时器,例如 CADisplayLink或自定义动画回调
  2. 使用 monospaced font 效果会更好
  3. 当文本为空或计时器失效时,此代码不处理重置
  4. 该效果的工作原理是在标签中设置整个文本,将其裁剪模式设置为仅显示其边界内的字符,最后从字符串的开头删除字符。我看不出真正有理由进行您在问题中描述的删除/插入“舞蹈”,但这将是一件微不足道的事情......

无论如何,我希望这是有道理的:)

关于ios - 通过删除和添加字母对 UILabel 产生选取框效果 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42205951/

相关文章:

ios - 隐藏/显示 UINavigationBar 会导致 UICollectionView 更改其框架

swift - 如何正确删除 SKSpriteNode

ios - 在 Swift 4 中获取远程通知设备 token ?

xcode - 使用 Xcode 和 iOS SDK 围绕任意点旋转图像

ios - 使用临时分发的设备崩溃

ios - 类型 'ViewController' 不符合协议(protocol)

ios - 避免致命车祸

ios - 我的应用程序二进制文件在 Xcode 中的哪里提交?

ios - 如何突出显示 UITextField 内的部分文本?

iphone - 升级到通用 iPhone/iPad 应用程序不太有效