簡體   English   中英

如何從NSLayoutConstraints獲取CGFloat值?

[英]How to get CGFloat value from NSLayoutConstraints?

我正在屏幕上工作,我想讓這個配置文件視圖循環。 但我沒有得到高度或寬度從imageView.frame.height在使用它layer.cornerRadius 請幫我。 謝謝。

在此輸入圖像描述

這是代碼供參考。

private func addImageView() {
        topView.addSubview(profilePicView)

        NSLayoutConstraint.activate([
            profilePicView.centerXAnchor.constraint(equalTo: topView.centerXAnchor),
            profilePicView.widthAnchor.constraint(equalTo: topView.heightAnchor, multiplier: 0.3)
            ])

        profilePicViewTopAnchor = profilePicView.topAnchor.constraint(equalTo: view.topAnchor, constant: 64)
        profilePicViewTopAnchor?.isActive = true

        profilePicViewHeightAnchor = profilePicView.heightAnchor.constraint(equalTo: topView.heightAnchor, multiplier: 0.3)
        profilePicViewHeightAnchor?.isActive = true
    }

而我正試圖獲得價值,

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print((profilePicViewHeightAnchor?.constant)!)
        profilePicView.layer.cornerRadius = (profilePicViewHeightAnchor?.constant)! / 2
        profilePicView.clipsToBounds = true

    }

解決了

在每個人的幫助下,我得到了這個解決方案,對我來說非常好,

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let radius = redView.frame.height * 0.3
        profilePicView.layer.cornerRadius = radius / 2
        profilePicView.clipsToBounds = true

        self.view.layoutIfNeeded()

    }

謝謝你們所有人。 真的很感激幫助。

這一定是因為你正在訪問的時間frameimageView ,布局約束不被奠定了autolayout 因此,如果您的imageView位於UIViewController類中,那么您應該override以下方法,然后訪問widthheight

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    print(imageView.frame.height)
}

如果imageView在自定義視圖中,那么您可以override以下方法然后訪問該frame

override func layoutSubviews() {
    super.layoutSubviews()

    print(imageView.frame.height)
}

請試試這對你有幫助。

imageView.layer.cornerRadius =  imageView.frame.size.height / 2
imageView.clipsToBounds = true

確保imageView的高度和寬度相同。 謝謝

您可以嘗試在標識符檢查器中設置故事板。 喜歡

在此輸入圖像描述

你也可以使用ViewDidAppear。因為此時Autolayout引擎開始布局Constraint。

override func viewDidAppear() {
    super.viewDidAppear()
    print(imageView.frame.height)
}

試試這個擴展:

 extension UIView {

        @IBInspectable
        /// Should the corner be as circle
        public var circleCorner: Bool {
            get {
                return min(bounds.size.height, bounds.size.width) / 2 == cornerRadius
            }
            set {
                cornerRadius = newValue ? min(bounds.size.height, bounds.size.width) / 2 : cornerRadius
            }
        }
    }

暫無
暫無

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

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