簡體   English   中英

如何更改UIView的寬高比

[英]How to change aspect ratio of a UIView

我有一個自定義UIView,它以編程方式使用自動布局來設置框架的大小。 為此,我將視圖的width屬性的約束設置為等於超級視圖的寬度,然后將寬高比的約束設置為某個硬編碼值

//width constraint
NSLayoutConstraint *widhtConstraint=[NSLayoutConstraint constraintWithItem:entryView
                                                                 attribute:NSLayoutAttributeWidth
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:scrollView
                                                                 attribute:NSLayoutAttributeWidth
                                                                multiplier:1.0f
                                                                  constant:8.0f];

[scrollView addConstraint:widhtConstraint];

//aspect ratio constraint
NSLayoutConstraint *aspectRatioConstraint=[NSLayoutConstraint constraintWithItem:entryView
                                                                       attribute:NSLayoutAttributeWidth
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:entryView
                                                                       attribute:NSLayoutAttributeHeight
                                                                      multiplier:80.0/27.0//aspect ratio same as formula view
                                                                        constant:0.0f];

[scrollView addConstraint:aspectRatioConstraint];

請參考圖片:

約束設置

我希望通過增加按鈕的高度來更改該框架的寬高比(“查看更多”),然后在觸摸同一按鈕時將其調整為原始尺寸。此外,我如何計算所控制視圖的總高度所有子視圖,以使每個子視圖都可見而不被裁剪。(基本上是標准折疊功能)

您可以在代碼中將寬高比作為變量,並使用代碼在諸如updateConstraints之類的方法中設置約束。

float aspectRatio; NSLayoutConstraint *aspectRatioConstraint=[NSLayoutConstraint constraintWithItem:entryView
                                                                   attribute:NSLayoutAttributeWidth
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:entryView
                                                                   attribute:NSLayoutAttributeHeight
                                                                  multiplier:self.aspectRatio//aspect ratio same as formula view
                                                                    constant:0.0f];

然后,當按下按鈕時,可以在action方法中將self.aspectRatio修改為合適,然后調用setNeedsUpdateConstraints和隨后的setNeedsLayout。

我還不清楚問題到底是什么,但是可以通過更改按鈕的約束來擴展/折疊超級視圖,這很容易:

在此處輸入圖片說明

如果這是您追求的目標,則可以在此處找到可下載的示例項目: https : //github.com/mattneub/Programming-iOS-Book-Examples/tree/master/bk2ch04p183animationAndAutolayout4

暫無
暫無

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

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