2017-05-31 19 views
1

我有一個自定義的視圖,我已經實現了,並且正在嘗試學習如何在不使用故事板的情況下使用自動佈局。我的問題是我需要使用框架來初始化視圖,還是隻需要執行一個空的init,然後使用自動佈局讓視圖自行計算寬度和高度?下面你會看到我已經嘗試添加框架,然後把自動佈局思考,我必須先放置一個框架,然後自動佈局改變它。視圖是否需要使用框架初始化,然後自動佈局更改或僅使用自動佈局?

let origin = CGPoint(x: 0.0, y: 0.0) 
    let size = CGSize(width: view.frame.width, height: 44.0) 

    let frame = CGRect(origin: origin, size: size) 

    customView = ExpandableHeadingView(frame: headingFrame) 

    customView.frame.size.height = 44.0 

    view.addSubview(customView) 

    view.topAnchor.constraint(equalTo: customView.topAnchor).isActive = true 
    view.leftAnchor.constraint(equalTo: customView.leftAnchor).isActive = true 
    view.rightAnchor.constraint(equalTo: customView.rightAnchor).isActive = true 
    view.heightAnchor.constraint(equalTo: customView.heightAnchor).isActive = true 

回答

4

您不應該設置框架。您只需爲自動佈局設置足夠的約束即可爲您設置它。你錯過了,可能是一個問題

的一件事是:

customView.translatesAutoresizingMaskIntoConstraints = false 

如果你在代碼中創建一個視圖,你通常需要手動設置這是能夠與自動佈局正確地使用它。

+0

我做你的建議,但它是還是行不通。我已經添加了這個'customView.heightAnchor.constraint(equalToConstant:44.0)'希望這會讓它顯示出來,但沒有任何東西。我甚至調試了視圖,約束沒有顯示出來。有關爲什麼高度限制不起作用的任何想法?我有一個左,右,和頂部設置,所以高度應該照顧我心中的最後一點。 – user3832583

+0

當你說它不工作時,你是什麼意思?究竟發生了什麼?我也看到你已經有一個高度約束設置在:view.heightAnchor.constraint(equalTo:customView.heightAnchor).isActive = true'。你刪除了這個嗎? – Dima

0

如果要使用自動佈局來佈局視圖,請不要使用此構造函數。

UIView(frame: CGRect) 

簡單的init與

UIView() 

而且你正在做的主要錯誤的觀點,就是要設置這些錨控制器的觀點,但你需要將它們設置爲你的觀點,你像這樣..

let customView = UIView() 
customView.backgroundColor = .blue 
customView.translatesAutoresizingMaskIntoConstraints = false 

view.addSubview(customView) 

customView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true 
customView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true 
customView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true 
customView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true 

而你很好去。

1

如果您在自定義UIView子類(接收幀作爲其唯一參數的子類)上重寫init方法,則必須在ViewController中創建它時給它一個框架。你可以做的是給它一個空框架,並用AutoLayout設置適當的位置和大小的約束。例如:

class CounterView: UIView { 
    override init(frame: CGRect) { 
     super.init(frame: frame) 
     translatesAutoresizingMaskIntoConstraints = false 
     backgroundColor = .red 
    } 

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

並在視圖控制器:

private var counterView: CounterView = { 
    let view = CounterView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) 
    return view 
}() 

.....

view.addSubview(counterView) 
counterView.leadingAnchor.constraint(equalTo: margin.leadingAnchor).isActive = true 
counterView.trailingAnchor.constraint(equalTo: margin.trailingAnchor).isActive = true 
counterView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing).isActive = true 
counterView.heightAnchor.constraint(equalToConstant: 200).isActive = true 

該代碼會產生這樣的:

Simulator Screenshot

相關問題