尝试在Swift中创建循环UIView时出错

时间:2015-06-05 13:33:06

标签: ios iphone swift uiview cornerradius

我的屏幕布局中有一个UIImageView,它根据容器视图尺寸动态调整大小。我想在圆形视图中转换它,我使用以下代码:

let dSize: CGFloat = min(imageview.frame.height, imageview.frame.width)
imageview.frame = CGRectMake(0, 0, dSize, dSize)
imageview.clipsToBounds = true
imageview.layer.cornerRadius = dSize/2.0
imageview.layer.borderWidth = 1.0
imageview.layer.borderColor = UIColor.whiteColor().CGColor

问题是生成的视图并不总是圆形的。为了达到这个效果,我必须在iPhone 4上将dSize除以 2.0 ,在iPhone 5 / 5s上用 1.7 除以 1.5 在iPhone 6 / 6s上。我无法弄清楚我做错了什么。

2 个答案:

答案 0 :(得分:5)

你能试试吗

//To make your imageView circular
imageView.layer.cornerRadius = imageView.frame.size.height/2;
imageView.layer.masksToBounds = YES;

//To add border
imageView.layer.borderColor = [UIColor whiteColor].CGColor;
imageView.layer.borderWidth = 2;

答案 1 :(得分:0)

viewDidLoad()对于UIImageView上的几何图形来说太早了,请尝试viewWillAppear(),因为这是保证几何图形可用的地方。

由于您使用的是自动布局,我建议您将其粘贴到viewDidLayoutSubviews()。每次发生自动布局时都会调用此方法。即使视图不改变方向,也可以多次。正如您在评论中所述,请务必在方法内部调用super(对于viewDidLoad()等视图控制器生命周期方法也应该这样做。

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.addCircleBorderToImageView(self.imageView)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.addCircleBorderToImageView(self.imageView)
}

// I made this UIView so it can be used with any view not just image views.
func addCircleBorderToImageView(imgView: UIView) {
    let dSize: CGFloat = min(imgView.frame.height, imgView.frame.width)
    imgView.bounds = CGRectMake(0, 0, dSize, dSize) // centered in container you want to use bounds over frame for this scenario
    imgView.clipsToBounds = true
    imgView.layer.cornerRadius = dSize/2.0
    imgView.layer.borderWidth = 1.0
    imgView.layer.borderColor = UIColor.whiteColor().CGColor
}