2017-04-18 24 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