我有一个UIButton
子类,它将从Storyboard初始化,我没有使用Xib。我想以编程方式添加UIActivityIndicatorView
。我的代码如下:import UIKit
class ResendConfirmButton: UIButton {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
configActivityIndicator()
}
override func layoutSubviews() {
super.layoutSubviews()
configStyling()
}
func configStyling() {
let buttonLayer = CAShapeLayer()
let buttonPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [UIRectCorner.bottomLeft, UIRectCorner.bottomRight], cornerRadii: CGSize(width: 2.0, height: 2.0))
buttonLayer.path = buttonPath.cgPath
buttonLayer.frame = bounds
layer.mask = buttonLayer
}
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
func configActivityIndicator() {
activityIndicator.center = CGPoint(x: bounds.midX, y: bounds.midY)
addSubview(activityIndicator)
activityIndicator.startAnimating()
}
}
但由于某种原因,未添加活动指示符。我已尝试将configActivityIndicator
移至layoutSubviews
但这也不起作用。调用此方法的正确位置在哪里并保持按钮自包含?
答案 0 :(得分:0)
在布局SubViews代码如下...
var activityIndicator = UIActivityIndicatorView()
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
activityIndicator.startAnimating()
self.addSubview(activityIndicator)
还有任何问题随时问我
答案 1 :(得分:0)
只需在centerIndicatorInButton()
中尝试此指标的更改位置即可class ResendConfirmButton: UIButton {
var buttonText: String?
var activityIndicator: UIActivityIndicatorView!
func showLoading() {
buttonText = self.titleLabel?.text
self.setTitle("", forState: UIControlState.Normal)
if (activityIndicator == nil) {
activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.color = UIColor.lightGrayColor()
}
// showSpinning
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(activityIndicator)
centerIndicatorInButton()
activityIndicator.startAnimating()
}
func hideLoading() {
self.setTitle(buttonText, forState: UIControlState.Normal)
activityIndicator.stopAnimating()
}
private func centerIndicatorInButton() {
let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: activityIndicator, attribute: .CenterX, multiplier: 1, constant: 0)
self.addConstraint(xCenterConstraint)
let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal, toItem: activityIndicator, attribute: .CenterY, multiplier: 1, constant: 0)
self.addConstraint(yCenterConstraint)
}
}