你能在Swift中为UIRefreshControl制作自定义视图吗?

时间:2018-04-17 22:42:39

标签: swift pull-to-refresh uirefreshcontrol

我想在视图中放置custom Activity Indicator并将其放在拉动内部以刷新视图。这种刷新特性适用于表格视图。我试过了......

    var headerView = UIView(frame: self.refreshControl.bounds)
    headerView.addSubview(activityIndicator)
    headerView.backgroundColor = UIColor.clear
    headerView.frame = refreshControl.bounds
    headerView.contentMode = .scaleAspectFit
    headerView.translatesAutoresizingMaskIntoConstraints = false
    refreshControl.tintColor = .clear
    refreshControl.addSubview(headerView)

1 个答案:

答案 0 :(得分:2)

是的,您可以通过调用addSubview方法将自定义视图添加到刷新控件。

// Outlet of table view
@IBOutlet weak var tbl      : UITableView!

// Create global variable of NVActivityIndicatorView
var nvActivityIndicator     : NVActivityIndicatorView?

override func viewDidLoad() {
    super.viewDidLoad()

    // Create refresh control and add as subview in your table view.
    let refreshControl = UIRefreshControl()
    refreshControl.backgroundColor = .red
    refreshControl.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
    tbl.addSubview(refreshControl)

    // Create NVActivityIndicator view and add as subview inside refresh control
    nvActivityIndicator = NVActivityIndicatorView(frame: refreshControl.bounds, type: NVActivityIndicatorType.ballRotate, color: .blue, padding: 0)
    nvActivityIndicator?.backgroundColor = refreshControl.backgroundColor
    nvActivityIndicator?.translatesAutoresizingMaskIntoConstraints = false

    refreshControl.addSubview(nvActivityIndicator!)

    // Add constraint to auto resize nvActivityIndicator as per refresh control view.
    let nvActivityIndicator_top = NSLayoutConstraint(item: nvActivityIndicator!, attribute: .top, relatedBy: .equal, toItem: refreshControl, attribute: .top, multiplier: 1, constant: 0)
    let nvActivityIndicator_bottom = NSLayoutConstraint(item: nvActivityIndicator!, attribute: .bottom, relatedBy: .equal, toItem: refreshControl, attribute: .bottom, multiplier: 1, constant: 0)
    let nvActivityIndicator_leading = NSLayoutConstraint(item: nvActivityIndicator!, attribute: .leading, relatedBy: .equal, toItem: refreshControl, attribute: .leading, multiplier: 1, constant: 0)
    let nvActivityIndicator_trailing = NSLayoutConstraint(item: nvActivityIndicator!, attribute: .trailing, relatedBy: .equal, toItem: refreshControl, attribute: .trailing, multiplier: 1, constant: 0)

    // Add constrains
    refreshControl.addConstraint(nvActivityIndicator_top)
    refreshControl.addConstraint(nvActivityIndicator_bottom)
    refreshControl.addConstraint(nvActivityIndicator_leading)
    refreshControl.addConstraint(nvActivityIndicator_trailing)

    // Set custom view background colour as per refreshControl background colour
    refreshControl.tintColor = refreshControl.backgroundColor
}

@objc func pullToRefresh() {
    // Start animation here.
    nvActivityIndicator?.startAnimating()
}

我希望这会对你有所帮助。