gpt4 book ai didi

ios - 子类化 UILabel 无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 14:18:48 24 4
gpt4 key购买 nike

我想在 View 中添加一个UILabel,当发生错误时它会向下滑动以向用户发送错误消息,3秒后它会向上滑动消失。它的原型(prototype)就像 Facebook 或 Instagram 展示的那样。我在许多 ViewController 中需要 errorLabel,所以我尝试子类化 UILabel。这是我的子类 ErrorLabel:

class ErrorLabel: UILabel {
var errorString: String?

func sendErrorMessage() {
self.text = errorString

showErrorLabel()
let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "hideErrorLabel", userInfo: nil, repeats: false)
}
func animateFrameChange() {
UIView.animateWithDuration(1, animations: { self.layoutIfNeeded() }, completion: nil)
}
func showErrorLabel() {
let oldFrame = self.frame
let newFrame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.height + 30, oldFrame.width)
self.frame = newFrame
self.animateFrameChange()
}
func hideErrorLabel() {
let oldFrame = self.frame
let newFrame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.height - 30, oldFrame.width)
self.frame = newFrame
self.animateFrameChange()
}
}

然后,我尝试将 errorLabel 添加到我的 ViewController 之一,如下所示:

class ViewController: UIViewController {
var errorLabel = ErrorLabel()

override func viewDidLoad() {
super.viewDidLoad()

let errorLabelFrame = CGRectMake(0, 20, self.view.frame.width, 0)
self.errorLabel.frame = errorLabelFrame
self.errorLabel.backgroundColor = translucentTurquoise
self.errorLabel.font = UIFont.systemFontOfSize(18)
self.errorLabel.textColor = UIColor.whiteColor()
self.errorLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(errorLabel)
self.view.bringSubviewToFront(errorLabel)
}

func aFunc(errorString: String) {
self.errorLabel.errorString = errorString
self.errorLabel.sendErrorMessage()
}
}

当我在 iOS 模拟器中运行它时,它没有按预期工作:

  1. errorLabel 水平显示在左侧,垂直显示在中间,只有 I... 应该是无效参数
  2. 1秒后,它到达预期位置,但宽度仍然不是self.view.frame.width
  3. 之后,没有任何反应,但 3 秒后它应该会向上滑动。

您能告诉我出了什么问题以及如何修复该错误吗?

最佳答案

我可能可以部分解决您的问题。希望对您有所帮助。

  • 当字符串比 View 长时,就会发生I...。为此,您需要增加 UILabel 的大小。
  • 要在 UILable 内对齐文本,请参阅 this
  • 要以动画方式消失,请在 UIView.animateWithDuration 的完成 block 中使用相同的代码。引用这个link

我建议您考虑使用扩展来完成您想要做的事情。

关于ios - 子类化 UILabel 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com