2017-04-18 47 views
2

我们将显示带有标签在一个表视图中呈矩形,当我们遇到一个错误:的iOS:视定位甩出的热点指标

enter image description here

有了这个代码:

// Fix location of message bar even as user scrolls table - per http://stackoverflow.com/q/7537858/47281 
override func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    let newY = self.tableView.contentOffset.y + self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.height 
    // Show rectangle using 0 and newY ... 

它运行良好,但在某些情况下无法正常工作,例如启用Personal Hotspot时。还有就是导航栏和状态矩形之间的间隙:

enter image description here

什么是始终定位导航栏下一些正确的方法是什么?

在第一种情况下,状态栏高度为20,但在第二种情况下为40.在这两种情况下,导航栏和内容偏移量都是相同的。即:

  • 情况#1:胶印:-64.0,导航栏高度:44.0状态栏高度:20.0
  • 情况#2:偏移:-64.0,导航栏高度:44.0状态栏高度:40.0

好像偏移不会因状态栏中的高度变化而增加。

更新:请参阅(我的)接受的答案。我确信有更好的方法..如果你知道一个,请添加到线程。

+0

set'definePresentationContext = true' –

回答

0

我的“穷人的解决方案”是为状态栏高度硬编码20:

var newY = self.tableView.contentOffset.y 
newY += self.navigationController!.navigationBar.frame.size.height 
newY += 20 

必须是一个更好的方式......但这似乎工作。

0

而不是定位您的消息与从框架派生的值,使用自动布局来定位它。

有实现这几方面 - 你可以做到这一点的一种方式将是以下几点:

//... assuming this is being called from the parent view controller 

    //safely unwrap the reference to the navigation controller 
    guard let navController = self.navigationController else { return } 
    let message = UIView() 

    //arbitrary styles for example only 
    message.backgroundColor = UIColor.blue 
    //set translatesAutoresizingMaskIntoConstraints so constraints will work 
    message.translatesAutoresizingMaskIntoConstraints = false 

    //create constraints 
    let height = NSLayoutConstraint(item: message, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50) 
    let equalWidth = NSLayoutConstraint(item: message, attribute: NSLayoutAttribute.width, relatedBy: .equal, toItem: navController.navigationBar, attribute: .width, multiplier: 1.0, constant: 0) 
    let alignBottom = NSLayoutConstraint(item: message, attribute: .top, relatedBy: .equal, toItem: navController.navigationBar, attribute: .bottom, multiplier: 1, constant: 0) 
    //apply constraints 
    message.addConstraint(height) 
    navController.view.addSubview(message) 
    navController.view.addConstraints([equalWidth, alignBottom]) 

这也可以使用VFL做 - 但其详细程度也许有点矫枉过正这里。

否则,有很大的库可以使用,使这更声明,减少锅炉板 - 像SnapKit

+0

前面的代码不正确,我对示例进行了更新以使其工作 – syllabix