谁能解释一下如何在 Swift 3.0 中实现这种效果?这几乎是一个字幕效果,但我不想滑动 UILabel。
如果能这样就好了
删除第一个字母并添加第 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
这是什么让你:
一些注意事项:
- 您可以使用一些其他机制来代替计时器,例如
CADisplayLink
或自定义动画回调 - 使用 monospaced font 效果会更好
- 当文本为空或计时器失效时,此代码不处理重置
- 该效果的工作原理是在标签中设置整个文本,将其裁剪模式设置为仅显示其边界内的字符,最后从字符串的开头删除字符。我看不出真正有理由进行您在问题中描述的删除/插入“舞蹈”,但这将是一件微不足道的事情......
无论如何,我希望这是有道理的:)
关于ios - 通过删除和添加字母对 UILabel 产生选取框效果 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42205951/