自定义加载指示器未显示在UIButton

时间:2019-12-28 16:17:41

标签: ios swift uikit

我已经设计了一个自定义动画作为活动指示器:

class LoadingIndicator: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
}

required init?(coder: NSCoder) {
    super.init(coder: coder)

}

func startLoadingIndicator() {
    //Animation Logic
}

func stopLoadingIndicator() {
    //Stop and hide animation
}
}

该类用作启动视图控制器中的情节提要板自定义类,并正确显示动画。

现在,我想在我的提交按钮上添加相同的类,以在等待网络响应时显示动画。

我已将以下函数添加到我的SubmitButton类中:

class SubmitButton: UIButton {

var originalButtonText: String?
var loadingIndicator: LoadingIndicator!

required init?(coder: NSCoder) {
    ...
}


...

//I call this method in my view controller:

func showLoading() {
    originalButtonText = self.titleLabel?.text
    self.setTitle("", for: .normal)

    if (loadingIndicator == nil) {
        loadingIndicator = initLoadingIndicator()
    }

    showAnimating()
}

func hideLoading() {
    ...
}

private func initLoadingIndicator() -> LoadingIndicator {
    let loadingIndicator = LoadingIndicator()
    return loadingIndicator
}

private func showAnimating() {
    loadingIndicator.translatesAutoresizingMaskIntoConstraints = false

    self.addSubview(loadingIndicator)
    centerLoadingIndicatorInButton()
    loadingIndicator.startLoadingIndicator()
}

private func centerLoadingIndicatorInButton() {
    let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: loadingIndicator, attribute: .centerX, multiplier: 1, constant: 0)
    self.addConstraint(xCenterConstraint)

    let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: loadingIndicator, attribute: .centerY, multiplier: 1, constant: 0)
    self.addConstraint(yCenterConstraint)
}
}

但是我看不到动画。我尝试添加一个UIActivityIndi​​catorView和一个简单的矩形视图,它们都出现在我的按钮上。因此,LoadingIndicator类或我如何对其进行初始化应该有问题。但是我找不到。即使没有动画,我也无法将LoadingIndicator视图放置在按钮内。我尝试给它提供背景色,但无处不在。我可以尝试什么?

解决方案

有两个问题:

  1. 因为我使用过translatesAutoresizingMaskIntoConstraints,所以宽度和高度锚点为零,因此我应该将它们定义为约束:

    让约束= [         loadingIndicator.widthAnchor.constraint(equalToConstant:34),         loadingIndicator.heightAnchor.constraint(equalToConstant:10),         loadingIndicator.centerXAnchor.constraint(equalTo:self.centerXAnchor),         loadingIndicator.centerYAnchor.constraint(等于:self.centerYAnchor)     ]

    NSLayoutConstraint.activate(constraints)
    
  2. 我在viewDidLoad中调用了动画方法,我尝试了viewWillAppear,现在终于可以看到动画了!

0 个答案:

没有答案