2017-04-08 40 views
-3

我正在努力將代碼中的一個按鈕添加到view的右上角。 有人可以解釋我怎麼做,而不需要設置左邊的約束?這會是左上方的V:|-10-[v0],H:|-10-[v0]會有什麼倒置呢?我試圖用這個:V:[v0]-10-|,H:[v0]-0-|,但它不工作,像我想的右上約束格式

在此先感謝!

+0

我不再使用VFL(sic?),而是使用錨來代替。但是看看你的「左上」限制,你確定那些工作嗎?假設* v0 *是您的按鈕,則表明您的按鈕在左側和右側都有10個點邊距,並且沒有垂直邊距。 – dfd

+0

@dfd thx對錯誤類型的點,但仍然與此設置它工作。 – yerpy

+0

好的。我看到更正,並知道我仍然記得如何閱讀VFL。 :-)我讀你的「右」引腳是*底*右,而不是*頂*。此外,您可以在水平方向上有一個類型,或者您希望在右邊沒有空白。你究竟看到了什麼? – dfd

回答

1

根據評論,我想就如何在右上角放置UIButton提供兩個答案。

VFL:

你的垂直引腳是右下角,不上頭。而不是V:[v0]-10-|,其中「管」字符(表示屏幕的邊界)在最後,將它放在開頭 - |-10-[v0]

假設你已經給出了按鈕某種高度/寬度 - 我認爲你有作爲「左上角」作品的代碼 - 這應該解決問題。

在iOS9推出,佈局錨(與佈局指南一起)是碼自佈局的第三方式。像NSLayoutConstraints一樣,這比VFL更不「視覺化」。但不像NSLayoutConstraints它不那麼冗長 - 因此更「快速」恕我直言。

要將UIButton固定到左上角,您仍然需要給自動佈局四件事 - 高度,寬度和X/Y位置。

// declare your button 
let v0 = UIButton() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // remember, you ALWAYS need to turn of the auto resize mask! 
    v0.translatesAutoresizingMaskIntoConstraints = false 

    view.addSubview(v0) 

    // create a square button 
    v0.widthAnchor.constraint(equalToConstant: 100.0)   
    v0.heightAnchor.constraint(equalToConstant: 100.0) 

    // pin the button 10 points from the left side of the view 
    v0.leadingAnchor.constraint(equalTo: v0.leadingAnchor, constant: 10)   

    // here's how you would pin the button 10 points from the right side of the view 
    // note the use of a negative here! 
    // v0.trailingAnchor.constraint(equalTo: v0.trailingAnchor, constant: -10)   

    // pin the button 10 points from the top of the view 
    v0.topAnchor.constraint(equalTo: v0.topAnchor, constant: 10) 

} 

NSLayoutConstraints,佈局錨有常數和乘數,而如果你的約束聲明一個名字,你可能會改變。

您可以將NSLayoutConstraintsNSLayoutGuides合併爲一些不錯的「自適應佈局」。這些指南的行爲像「間隔/不可見」UIViews,除了開銷 - 它們不是視圖。您可以獲得一組Apple標準邊距(UIView.layoutMarginsGuide),也可以創建一組尺寸相同的動態指南來平等地分配空間。

這是關於layout anchorslayout guides的兩篇博客。這些示例是用Swift 2編寫的,但Swift 3沒有語法變化。