如何在以编程方式创建的按钮上添加 Spinner Indicator

How to add Spinner Indicator on Programmatically created Button

你好,我已经在我的静态 TableView 上动态创建了按钮,就像这样

override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height))

  let button   = UIButton(type: UIButtonType.System) as UIButton
        button.frame = CGRectMake(0, 0, 414, 65)

        button.setTitle(buttonTitle, forState: UIControlState.Normal)
        button.addTarget(self, action:buttonAction, forControlEvents: UIControlEvents.TouchUpInside)
        button.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Normal)
        button.titleLabel?.font = UIFont(name: Variables.MONTESERRAT_REGULAR, size: 20.0)
  button.backgroundColor = UIColor().blueColor()       //top
         footerView.addSubview(button!)


        return footerView
}

我想在单击按钮时在按钮顶部显示微调器。我知道如何制作点击功能或如何创建微调器。我只是不知道如何将微调器放在按钮顶部而不是标题上,这样当用户单击按钮时,标题会隐藏并且微调器会在标题位置移动。我希望你明白我在说什么

UIActivityIndicatorView *myspinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [myspinner setCenter:button.center];
    [button addSubview:myspinner];
  1. 您创建了一个微调器 (UIActivityIndicatorView),并使其自动隐藏 (setHidesWhenStopped:)
  2. 您将它作为子视图添加到您的按钮 (addSubview)
  3. 你把它放在按钮的中央 (setCenter:)
  4. 在按下按钮时将标题设置为空字符串 (setTitle:forControlState:) 并且 运行 微调器 (startAnimating)

这是我通常的做法,您可以使用一些不同的行为:

let spinner = UIActivityIndicatorView(activityIndicatorStyle: .White)

spinner.frame = CGRect(x: -20.0, y: 6.0, width: 20.0, height: 20.0) // (or wherever you want it in the button)
spinner.startAnimating()
spinner.alpha = 0.0

button.addSubview(spinner)

您可以相应地更改 alpha。或者使用隐藏属性、stop/start 动画等

这是我的 swift 版本

let loginSpinner: UIActivityIndicatorView = {
    let loginSpinner = UIActivityIndicatorView(activityIndicatorStyle: .white)
    loginSpinner.translatesAutoresizingMaskIntoConstraints = false
    loginSpinner.hidesWhenStopped = true
    return loginSpinner
}()

然后在我的 viewDidLoad 函数中:

    loginButton.addSubview(loginSpinner)
    loginSpinner.centerXAnchor.constraint(equalTo: loginButton.centerXAnchor).isActive = true
    loginSpinner.centerYAnchor.constraint(equalTo: loginButton.centerYAnchor).isActive = true

最后在需要的地方调用 loginSpinner.startAnimating()loginSpinner.stopAnimating() 函数。

注意:当开始和停止动画时,我还禁用了按钮,因此取消设置禁用按钮的标题,以便微调器替换标题 loginButton.setTitle("", for: .disabled) // clear the title when it is disabled to just show the spinner