在iOS应用中改变UIRefreshControl指示器的初始位置

6

我正在开发一个使用UITableView和UIRefreshControl的iOS应用程序。

我想将UIRefreshControl指示器的初始位置从默认位置向下移动50像素。我编写了以下代码。

然而,初始位置没有改变。它仍然保持在原来的位置。

你能告诉我如何解决这个问题吗?

CGFloat customRefreshControlHeight = 50.0f;
CGFloat customRefreshControlWidth = 320.0f;
CGRect customRefreshControlFrame = CGRectMake(0.0f,
                                              customRefreshControlHeight,
                                              customRefreshControlWidth,
                                              customRefreshControlHeight);
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] initWithFrame:customRefreshControlFrame];
refreshControl.tintColor = [UIColor blackColor];
[refreshControl addTarget:self action:@selector(onRefresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];

我认为你可以在这里找到一个合适的答案: https://dev59.com/LGQm5IYBdhLWcg3w0RxV#59489992 - Rufat Mirza
3个回答

7

一种解决方案是创建UIRefreshControl的子类并重写frame属性。以下代码在我测试的所有情况下都有效。您也可以通过应用变换而不是重写frame来实现它。在viewDidLayoutSubviews中设置框架无效,因为iOS 11不支持。

class OffsetableRefreshControl: UIRefreshControl {

  var offset: CGFloat = 64
  override var frame: CGRect {
    set {
      var rect = newValue
      rect.origin.y += offset
      super.frame = rect
    }
    get {
      return super.frame
    }
  }

}

这对于在UICollectionView中进行刷新控制非常有效!谢谢。 - Filip
这个不起作用...在哪里添加这段代码? - Khris Vandal

6

直接设置框架不起作用,但您仍然可以使用AutoLayout将refreshControl放置在所需位置。只是不要忘记将translatesAutoresizingMaskIntoConstraints设置为false

例如,此代码将refreshControl设置在屏幕中央。

let refreshControl = UIRefreshControl()
collectionView.refreshControl = refreshControl
refreshControl.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint(item: refreshControl, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: refreshControl, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0).isActive = true

这个不再起作用了。 - Khris Vandal

1

只是简单的(Swift)

   override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        refreshController.frame = CGRectMake(refreshController.bounds.origin.x,
                                              50.0,
                                              refreshController.bounds.size.width,
                                              refreshController.bounds.size.height);
        refreshController.superview?.sendSubviewToBack(refreshController) // for fix overlap tableview
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接