2017-08-10 89 views
0

我有一个来自类的视图,我想将角半径设置为其宽度的一半。在视图加载后在视图中设置角点半径

宽度是使用自动布局制作的计算属性。所以,一般情况下我设定的圆角半径财产viewWillLayoutSubviews()像这样

override func viewWillLayoutSubviews() { 
    super.viewWillLayoutSubviews() 

    c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 
} 

但largeProfileImage是不是被viewDidLoad中后称为初始视图和动画我它轻拍姿态。以下是视图在屏幕上动画的位置。它是在这个相同的功能中创建的。

 //I tried setting the cornerRadius here as well but it isn't setting. 

    //c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 


    self.view.layoutIfNeeded() 

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { 

     self.profileImageContainerCenterY?.constant = -(c.profileImageContainer.frame.height) * 2 
     self.profileSettingsContainerCenterY?.constant = 0 

     c.profileSettingsContainer.alpha = 1 
     c.largeProfileImage.alpha = 1 

     self.view.layoutIfNeeded() 
    }, completion: { (completed) in 
     self.view.layoutIfNeeded() 
}) 

编辑:

这里的profileImage

let largeProfileImage: UIImageView = { 
    let pv = UIImageView() 
    pv.contentMode = .scaleAspectFill 
    pv.layer.masksToBounds = true 
    pv.clipsToBounds = true 
    pv.image = UIImage(named: "user") 

    pv.translatesAutoresizingMaskIntoConstraints = false 
    return pv 
}() 
+0

从类视图添加视图是在声明类的相同控制器上?或者将控制器A中的类和控制器A中的类的视图添加到控制器B中? –

+0

您是否尝试在viewDidLayoutSubviews方法中添加cornerRadius?请尝试使用这种方法,可能会在所有视图布局后帮助设置cornerRadius – 3stud1ant3

+0

您需要添加'largeProfileImage.layer.masksToBounds = false'和'largeProfileImage .clipsToBounds = true' – Annjawn

回答

1

我成功地调试了这个问题。

由于宽度为一个计算的属性是0的布局被布置意

c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 

self.view.layoutIfNeeded() 

导致零角半径之前。

因此,解决办法...

是调用它之后的宽度来设置转角半径的宽度计算之后。

self.view.layoutIfNeeded() 

c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 
0

为了正确的动画更改顺序是这样的。

self.profileImageContainerCenterY?.constant = -(c.profileImageContainer.frame.height) * 2 
    self.profileSettingsContainerCenterY?.constant = 0 
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { 
    c.profileSettingsContainer.alpha = 1 
    c.largeProfileImage.alpha = 1 
    self.view.layoutIfNeeded() 
}, completion: nil) 
+0

动画很好,它会生成动画。问题是拐角半径未设置 – Stefan

+0

在设置拐角半径后添加c.largeProfileImage.clipsToBounds = true。 –

+0

也为什么你要在完成处理程序中调用layoutIf。这不是必需的。 –

0

下三行是必要得到一个圆形图像 -

image.layer.cornerRadius = image.frame.width/2 
image.layer.masksToBounds = false 
image.clipsToBounds = true 

您可能会看到一个圆形的UIImage但你也可能会发现圆内的图像平方,解决你可能有玩contentMode。大部分时间.scaleAspectFill都能胜任。

+0

创建视图时无法访问自我...将在编辑中包含视图。 – Stefan

+0

在你的更新中,它应该是'masksToBounds = false' – Annjawn

+0

我认为这与我从类中获取视图并且没有正确引用视图有关。或者宽度是一个计算属性的事实,当宽度等于0时,角半径被设置。但是我不能在函数中调用viewWillLayoutSubviews。 – Stefan