LoginSignup
8

More than 3 years have passed since last update.

SwiftでUIActivityIndicatorViewを使う

Last updated at Posted at 2016-03-09

使い方はとてもシンプル。
定義もこれだけ。

import Foundation
import UIKit

//
//  UIActivityIndicatorView.h
//  UIKit
//
//  Copyright (c) 2005-2015 Apple Inc. All rights reserved.
//

public enum UIActivityIndicatorViewStyle : Int {

    case WhiteLarge
    case White
    case Gray
}

@available(iOS 2.0, *)
public class UIActivityIndicatorView : UIView, NSCoding {

    public init(activityIndicatorStyle style: UIActivityIndicatorViewStyle) // sizes the view according to the style
    public init(frame: CGRect)
    public init(coder: NSCoder)

    public var activityIndicatorViewStyle: UIActivityIndicatorViewStyle // default is UIActivityIndicatorViewStyleWhite
    public var hidesWhenStopped: Bool // default is YES. calls -setHidden when animating gets set to NO

    @available(iOS 5.0, *)
    public var color: UIColor?

    public func startAnimating()
    public func stopAnimating()
    public func isAnimating() -> Bool
}

コードで使う場合

生成して破棄まで1つのメソッド内で行う場合、プロパティに持ちたくないと思うのでこんな風に使う。デフォルトで hidesWhenStopped = true となっているので stopAnimating()を呼ぶだけで隠れる。

// 生成
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
indicator.center = CGPointMake(view.bounds.midX, view.bounds.midY)
// または UIActivityIndicatorView(frame: CGRectMake)の後、Styleを設定
view.addSubview(indicator)

// スタート
indicator.startAnimating()
refresh(completionHandler: {
    // ストップ
    indicator.stopAnimating()
    indicator.removeFromSuperview();
})

xibで使う場合

上記と同じ要領でxibで使うとアニメーション後もUIActivityIndicatorViewが残る。
xibで生成する場合とコードで生成する場合とでhidesWhenStoppedのデフォルト値が変わることが原因。Hides When Stoppedにチェックを入れて使いましょう。
Screen Shot 2016-03-09 at 9.24.07 PM.png

xibで生成する場合は @IBOutlet で接続しているのでプロパティとしてクラス内のどこからでも操作可能となる。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8