2017-10-21 32 views
1

我正在構建一個UIPageViewController,它具有基於視圖數組中視圖高度的可變頁數。如何在添加到子視圖之前獲取UIView的寬度和高度?

我有一個叫做BlockView類,看起來像這樣:

final class BlockView: UIView { 

    init(viewModel: BlockViewModel) { 
     super.init(frame: .zero) 

     let primaryLabel = UILabel() 
     primaryLabel.text = viewModel.labelText 
     addSubview(primaryLabel) 

     constrain(primaryLabel) { 
      $0.top == $0.superview!.top + 8 
      $0.bottom == $0.superview!.bottom - 8 
      $0.left == $0.superview!.left + 8 
      $0.right == $0.superview!.right - 8 
     } 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 
} 

我想什麼,能夠做的是循環通過我BlockViews的陣列和運行print(blockView.frame)和看到未幀零。

現在我知道我將frame設置爲.zero裏面的BlockView.init。這是因爲我希望視圖根據其標籤來確定自己的尺寸。

是否有我需要運行來實現這個功能?

感謝

+0

雖然我個人不使用框架(自動佈局來代替),從聲音你不能*做到這一點。兩者都基於視圖和控制器生命週期。是的,**兩個**都不知道它們在'init'上的「框架」 - 除非控制器*足夠遠以便給它*視圖的框架*或者*提供特定的框架。所以我想問題是 - 你有什麼'UIViewController'代碼可能有幫助? – dfd

+0

我總是使用自動佈局。我面臨的棘手的部分,我想要添加視圖作爲子視圖,如果它適合沒有溢出,或者我想爲UIPageViewController創建一個新的視圖控制器,然後*然後*添加元素。這需要調整 –

+0

BlockView有沒有限制?如果添加約束,手動框架設置將不起作用。 –

回答

1

嘗試sizeThatFits(_:)來計算的話,而不把它給上海華。該方法的唯一參數是CGSize,它表示應顯示的邊界。例如,如果你知道上海華(例如,340點)的寬度,你想知道多少會採取高度:

let expectedSize = view.sizeThatFits(CGSize(width: 340, height: .greatestFiniteMagnitude)) 

但是,你BlockView似乎不具備設置還適當限制。你用super.init(frame: .zero)初始化它 - 因此它的大小爲0,0。

而且你的約束不改變這種狀況,如:

constrain(primaryLabel) { 
    $0.centerY == $0.superview!.centerY 
    $0.left == $0.superview!.left + 8 
} 

這看起來像你設置的標籤塊視圖中心的Y軸的中心,以及標籤到左側被定位視圖的左側錨點。如果blockView已經具有尺寸,那將正確定位標籤。但現在,塊視圖的大小完全不受標籤大小的影響。我想你會想將標籤限制在blockView的左側,右側,頂部和底部錨點,以便當您嘗試計算blockView的大小時,自動佈局必須首先計算標籤的大小並根據在這個大小的blockView本身。

一個可能的解決方案(我用的錨基於自動版式語法),你可以嘗試把對的BlockView初始化:

primaryLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true 
primaryLabel.topAchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true 
primaryLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true 
primaryLabel.bottomAnchor.constraint(equalTo: secondaryLabel.topAnchor, constant: -8).isActive = true 
secondaryLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true 
secondaryLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true 
secondaryLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true 
+0

這假定視圖有一個大小,對吧?我正在運行這個,'let width = UIScreen.main.bounds.size.width - 24.0'' print(view.sizeThatFits(CGSize(width:width,height:.greatestFiniteMagnitude)))'getting(0,0) –

+0

看到更新的ansewer –

+0

我更新了我原來的帖子,並根據你的回答提供了新的約束條件,但我仍然在(0,0)運行'sizeThatFits' –

相關問題