UILabel에서 텍스트를 애니메이션으로 변경합니다.
새 텍스트 값을 다음으로 설정하는 중입니다.UILabel
현재 새 텍스트는 정상적으로 나타납니다.하지만 새 텍스트가 나타나면 애니메이션을 추가하고 싶습니다.새로운 텍스트의 모양을 애니메이션화하려면 어떻게 해야 하는지 궁금합니다.
작동하는지 궁금하고, 완벽하게 작동합니다!
목표-C
[UIView transitionWithView:self.label
duration:0.25f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.label.text = rand() % 2 ? @"Nice nice!" : @"Well done!";
} completion:nil];
스위프트 3, 4, 5
UIView.transition(with: label,
duration: 0.25,
options: .transitionCrossDissolve,
animations: { [weak self] in
self?.label.text = (arc4random()() % 2 == 0) ? "One" : "Two"
}, completion: nil)
목표-C
진정한 교차 용해 전환(이전 레이블은 페이드아웃되고 새 레이블은 페이드인)을 수행하려면 페이드가 보이지 않도록 해야 합니다.텍스트가 변경되지 않은 경우에도 원하지 않는 깜박임이 발생합니다.
대신 다음 방법을 사용합니다.
CATransition *animation = [CATransition animation];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = kCATransitionFade;
animation.duration = 0.75;
[aLabel.layer addAnimation:animation forKey:@"kCATransitionFade"];
// This will fade:
aLabel.text = "New"
참고:두 숫자 사이에 UI 레이블 텍스트를 애니메이션화하시겠습니까?
iOS 10, 9, 8에서의 시연:
Xcode 8.2.1 및 7.1, iOS 10 ~ 8.0의 목표를 사용하여 테스트되었습니다.
전체 프로젝트를 다운로드하려면 Swift Recipes에서 SO-3073520을 검색하십시오.
스위프트 4
UILabel(또는 해당 UIView)을 페이드하는 적절한 방법은Core Animation Transition
내용이 변경되지 않으면 깜박이지 않고 검은색으로 바래지 않습니다.
휴대가 가능하고 깨끗한 솔루션은 다음을 사용하는 것입니다.Extension
Swift에서(가시적 요소를 변경하기 전에 호출)
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
호출은 다음과 같습니다.
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
GitHub에서 이 솔루션을 찾고 Swift Recipes에 대한 추가 세부 정보를 찾으십시오.
iOS4부터 블록으로 수행할 수 있습니다.
[UIView animateWithDuration:1.0
animations:^{
label.alpha = 0.0f;
label.text = newText;
label.alpha = 1.0f;
}];
이것이 작동할 수 있는 코드입니다.
[UIView beginAnimations:@"animateText" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:1.0f];
[self.lbl setAlpha:0];
[self.lbl setText:@"New Text";
[self.lbl setAlpha:1];
[UIView commitAnimations];
위의 SwiftArchitect 솔루션의 Swift 4.2 버전(훌륭하게 작동):
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
호출:
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
UILabel 확장 솔루션
extension UILabel{
func animation(typing value:String,duration: Double){
let characters = value.map { $0 }
var index = 0
Timer.scheduledTimer(withTimeInterval: duration, repeats: true, block: { [weak self] timer in
if index < value.count {
let char = characters[index]
self?.text! += "\(char)"
index += 1
} else {
timer.invalidate()
}
})
}
func textWithAnimation(text:String,duration:CFTimeInterval){
fadeTransition(duration)
self.text = text
}
//followed from @Chris and @winnie-ru
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
단순 호출 함수:
uiLabel.textWithAnimation(text: "text you want to replace", duration: 0.2)
여러분, 많은 조언 감사합니다.이것이 장기적으로 도움이 되기를 바랍니다.
Swift 5를 사용하면 다음의 두 가지 Playground 코드 샘플 중 하나를 선택하여 당신의 컴퓨터에 애니메이션을 만들 수 있습니다.UILabel
의 텍스트가 일부 교차 용해 애니메이션으로 변경됩니다.
#1. 사용하기UIView
의 수업 방식
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Car"
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func toggle(_ sender: UITapGestureRecognizer) {
let animation = {
self.label.text = self.label.text == "Car" ? "Plane" : "Car"
}
UIView.transition(with: label, duration: 2, options: .transitionCrossDissolve, animations: animation, completion: nil)
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
#2. 사용 및CALayer
의 방법
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let label = UILabel()
let animation = CATransition()
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Car"
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
// animation.type = CATransitionType.fade // default is fade
animation.duration = 2
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func toggle(_ sender: UITapGestureRecognizer) {
label.layer.add(animation, forKey: nil) // The special key kCATransition is automatically used for transition animations
label.text = label.text == "Car" ? "Plane" : "Car"
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
Swift 2.0:
UIView.transitionWithView(self.view, duration: 1.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
self.sampleLabel.text = "Animation Fade1"
}, completion: { (finished: Bool) -> () in
self.sampleLabel.text = "Animation Fade - 34"
})
OR
UIView.animateWithDuration(0.2, animations: {
self.sampleLabel.alpha = 1
}, completion: {
(value: Bool) in
self.sampleLabel.alpha = 0.2
})
애니메이션의duration
그리고.timingFunction
속성을 생략할 수 있습니다. 이 경우 기본값은 다음과 같습니다.0.25
그리고..curveEaseInEaseOut
,각각 다음과 같다.
let animation = CATransition()
label.layer.add(animation, forKey: nil)
label.text = "New text"
다음과 같습니다.
let animation = CATransition()
animation.duration = 0.25
animation.timingFunction = .curveEaseInEaseOut
label.layer.add(animation, forKey: nil)
label.text = "New text"
Swift 4.2 솔루션(4.0 응답 및 컴파일할 새 열거형 업데이트)
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}
이를 위한 해결책이 하나 더 있습니다.여기에 설명되어 있습니다.아이디어는 하위 분류입니다.UILabel
및 우선순위action(for:forKey:)
다음과 같은 방식으로 작동합니다.
class LabelWithAnimatedText: UILabel {
override var text: String? {
didSet {
self.layer.setValue(self.text, forKey: "text")
}
}
override func action(for layer: CALayer, forKey event: String) -> CAAction? {
if event == "text" {
if let action = self.action(for: layer, forKey: "backgroundColor") as? CAAnimation {
let transition = CATransition()
transition.type = kCATransitionFade
//CAMediatiming attributes
transition.beginTime = action.beginTime
transition.duration = action.duration
transition.speed = action.speed
transition.timeOffset = action.timeOffset
transition.repeatCount = action.repeatCount
transition.repeatDuration = action.repeatDuration
transition.autoreverses = action.autoreverses
transition.fillMode = action.fillMode
//CAAnimation attributes
transition.timingFunction = action.timingFunction
transition.delegate = action.delegate
return transition
}
}
return super.action(for: layer, forKey: event)
}
}
사용 예:
// do not forget to set the "Custom Class" IB-property to "LabelWithAnimatedText"
// @IBOutlet weak var myLabel: LabelWithAnimatedText!
// ...
UIView.animate(withDuration: 0.5) {
myLabel.text = "I am animated!"
}
myLabel.text = "I am not animated!"
이것은 @SwiftArchitect의 코드를 기반으로 한 C# UIView 확장 방법입니다.자동 레이아웃이 사용되고 레이블의 텍스트에 따라 컨트롤을 이동해야 하는 경우, 이 호출 코드는 레이블 자체 대신 레이블의 수퍼뷰를 전환 뷰로 사용합니다.작업을 더 캡슐화하기 위해 람다 식을 추가했습니다.
public static void FadeTransition( this UIView AView, double ADuration, Action AAction )
{
CATransition transition = new CATransition();
transition.Duration = ADuration;
transition.TimingFunction = CAMediaTimingFunction.FromName( CAMediaTimingFunction.Linear );
transition.Type = CATransition.TransitionFade;
AView.Layer.AddAnimation( transition, transition.Type );
AAction();
}
호출 코드:
labelSuperview.FadeTransition( 0.5d, () =>
{
if ( condition )
label.Text = "Value 1";
else
label.Text = "Value 2";
} );
다음에서 이 작업을 수행하려면Swift
지연된 상태에서 다음을 시도합니다.
delay(1.0) {
UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
self.yourLabel.text = "2"
}, completion: { finished in
self.delay(1.0) {
UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
self.yourLabel.text = "1"
}, completion: { finished in
})
}
})
}
@http - https://stackoverflow.com/a/24318861/1982051 에서 만든 다음 함수를 사용합니다.
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
스위프트 3에서 이것이 될 것입니다.
func delay(_ delay:Double, closure:()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.after(when: when, execute: closure)
}
언급URL : https://stackoverflow.com/questions/3073520/animate-text-change-in-uilabel
'sourcecode' 카테고리의 다른 글
Visual Studio에서 이클립스의 ALT+UP/DOWN(이동선)에 해당하는 것은 무엇입니까? (0) | 2023.04.29 |
---|---|
ASP 간의 연결 풀 문제를 해결하려면 어떻게 해야 합니까?NET 및 SQL 서버? (0) | 2023.04.29 |
bash 셸 스크립트(unix)에서 .profile을 다시 로드하시겠습니까? (0) | 2023.04.29 |
VBA(Excel 2010)에서 기본 사례를 변수로 복원하는 방법은 무엇입니까? (0) | 2023.04.29 |
배포 대상은 무엇을 의미합니까? (0) | 2023.04.29 |