簡體   English   中英

iOS自動布局和縱向和橫向的大小類

[英]iOS auto-layout and size class in portrait and landscape

我使用自動布局和大小類設計我的布局。 現在我的肖像畫布局了 在此輸入圖像描述

單擊更改按鈕時,藍色視圖的框架和紅色視圖的框架將交換

    @IBAction func change(sender: AnyObject) {

    let frame = view1.frame
    view1.frame = view2.frame
    view2.frame = frame
}

現在它看起來像:

在此輸入圖像描述

然后我將iPhone的方向更改為橫向,我希望紅色視圖將保持在頂部位置,但是,它會更改為: 在此輸入圖像描述

有人可以幫我弄清楚如何實現這個嗎? 謝謝你的幫助! 以下是示例項目: https//github.com/SomnusLee1988/SamplePorject.git

我剛剛在你的github repo上提交了一個pull請求,它有我解決這個問題的方法。 這是我做的事情:

1)我從故事板中刪除了兩個視圖,並在viewController以編程方式添加它們。

2)現在,約束以編程方式添加到viewController的兩個視圖

3)當點擊“ Change按鈕時,將刪除約束,然后將它們添加回與先前的相反(即,view1常量變為view2約束,view2約束變為view1約束)。

以下是一些相關代碼:

@IBAction func change(sender: AnyObject) {
    // Remove existing constraints
    self.firstView.removeConstraints(self.firstView.constraints)
    self.secondView.removeConstraints(self.secondView.constraints)
    self.firstView.removeFromSuperview()
    self.secondView.removeFromSuperview()

    // Decide which view will recieve which constraints now based on their current sizes
    if firstView.frame.height == 50 {
        self.createAutoLayoutForViews(self.secondView, view2: self.firstView)
    } else {
        self.createAutoLayoutForViews(self.firstView, view2: self.secondView)
    }
}

要查看完整的實現,請在此處查看我的pull request或fork on github repo

注意:我只是將視圖隨機大小。 如果希望它們的大小不同,則需要更改兩個視圖的自動布局約束

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM