ios - 如何从 NSLayoutConstraints 获取 CGFloat 值?

标签 ios swift autolayout constraints

我在屏幕上工作,我想让这个个人资料 View 循环显示。但是我没有从 imageView.frame.height 获取高度或宽度以在 layer.cornerRadius 中使用它。请帮我。谢谢。

enter image description here

这里是引用代码。

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()

    }

谢谢大家。非常感谢您的帮助。

最佳答案

这一定是因为当您访问 imageViewframe 时,autolayout 没有布置布局约束。因此,如果您的 imageViewUIViewController 类中,那么您应该覆盖下面的方法,然后访问 width高度

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    print(imageView.frame.height)
}

如果 imageView 在自定义 View 中,那么您可以覆盖下面的方法,然后访问 frame

override func layoutSubviews() {
    super.layoutSubviews()

    print(imageView.frame.height)
}

关于ios - 如何从 NSLayoutConstraints 获取 CGFloat 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53476288/

相关文章:

objective-c - 如何在 Storyboard中设置初始 ViewController 的委托(delegate)

ios - 类在目标中被多次链接

ios - 在 Xcode 帮助查看器中隐藏 Swift 文档

ios - 如何在 UITableView 标题上方添加具有视差效果的图像并保持标题粘性?

objective-c - 以编程方式使用自动布局对齐 NSView

android - 尝试使用他们的 Apportable SDK 进行构建

ios - Swift 3.0 向导航栏添加一个右键

ios - iOS 中不同设备上的图像 1x、2x 和 3x 问题

ios - "The view hierarchy is not prepared for the constraint" swift 3 错误

objective-c - 接受UIButtons和UIViews作为方法的参数