2017-10-06 197 views
2

我一直在從Apple製作iOS教程;開始開發iOS應用程序。 https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ImplementingACustomControl.html#//apple_ref/doc/uid/TP40015214-CH19-SW1heightAnchor.constraint不起作用(使用Swift的Apple FoodTracker教程)

在教程中,我在水平堆棧視圖中添加了一個大小約爲44.0x44.0的按鈕。 但是,模擬器會顯示一個更大的按鈕。

looks the size constraints do not work.

我的代碼如下。你能給意見修復嗎?

class RatingControl: UIStackView { 
    //MARK: Initialization 
    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setupButtons() 
    } 
    required init(coder: NSCoder) { 
     super.init(coder: coder) 
     setupButtons() 
    } 

    //MARK: Private Methods 
    private func setupButtons() { 
     let button = UIButton() 
     button.backgroundColor = UIColor.red 
     // Add constraints 
     button.translatesAutoresizingMaskIntoConstraints = false 
     button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true 
     button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true 
     addArrangedSubview(button) 
    } 
} 

該問題是通過更改StackView的屬性來解決的。

+0

什麼是限制,對齊和分佈特性你的'RatingControl'(這是一個子類'UIStackView')? – DonMag

+0

@DonMag對齊和分配都設置爲填充。 –

+0

確定 - 堆棧視圖可能*看起來像混亂的大小。我說「似乎」,因爲他們的行爲是按照設計的,但他們的設計方式並不總是很清楚。將對齊更改爲Leading應該修正寬度...並將Distribution分配給Equal Spacing應該可以修復高度...但是,根據您如何設置Constraints,您可能需要額外的調整。 – DonMag

回答

3

我有同樣的問題。這是因爲我沒有將新的水平堆棧視圖拖到現有的垂直堆棧視圖中。相反,我將它拖入主視圖。如果您查看「文檔大綱」,則新的StackView應該是第一個垂直堆棧視圖的子視圖,並且位於Photo Image View下方。

它在說明中,但對我來說還不清楚。