简体   繁体   English

以编程方式更改视图的高度和宽度会导致使用swift在iOS中出现意外行为

[英]Changing Height and Width of View programatically leads to unexpected behaviour in iOS using swift

I was making a view rounded by using 我正在通过使用圆形视图

dashboardView.layer.cornerRadius = dashboardView.frame.height/2

And it was working. 它工作正常。 Then I changed the height and width of my View with this method 然后我用这种方法改变了View的高度和宽度

dashboardView.frame = CGRect(x: screenSize.width/2,y: 300,width: 200,height: 200)

Now when I try to make it round by using same method, it's not working. 现在,当我尝试使用相同的方法进行循环时,它不起作用。 I was also adding a gradient layer on the view with this method 我还使用此方法在视图上添加了渐变图层

    let gradient: CAGradientLayer = CAGradientLayer()
    let endingColorOFGradient = UIColor(colorLiteralRed: 133/255, green: 210/255, blue: 230/255, alpha: 1.0).CGColor
    let startingColorOfGradient = UIColor(colorLiteralRed: 50/255, green: 189/255, blue: 170/255, alpha: 1.0).CGColor
    gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
    gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.frame = CGRect(x: 0, y: 0, width: dashboardView.layer.frame.width, height: dashboardView.layer.frame.height)
    gradient.colors = [startingColorOfGradient , endingColorOFGradient]
    self.dashboardView.layer.insertSublayer(gradient, atIndex:0)
    // making gradient round
    gradient.cornerRadius = dashboardView.frame.height/2

And after changing the size of View gradient, the layer does become round but my View does not. 在更改View渐变的大小后,图层确实变圆,但我的视图不会。

This is the View I created. 这是我创建的视图。 Actually I want to change its size according to device. 实际上我想根据设备改变它的大小。 It should be small on iphone 5 and larger on iphone 6+ 在iphone 5上它应该很小,在iphone 6+上应该更大 在此输入图像描述

This is what I am getting 这就是我得到的 在此输入图像描述 I am stuck at this point. 我被困在这一点上。

call dashboardView.layer.cornerRadius = dashboardView.frame.height/2 again after setting gradient because you are changing frame so it's height should be different so your dashboardView.frame.height/2 have different value. 在设置渐变后再次调用dashboardView.layer.cornerRadius = dashboardView.frame.height/2 ,因为您正在更改框架,因此它的高度应该不同,因此您的dashboardView.frame.height/2具有不同的值。

and try to set clipstobounds to true for dashboardView if required. 如果需要,尝试将clipstobounds设置为true ,以用于dashboardView

The problem was Autolayout constraints. 问题是Autolayout约束。

I was trying to change the size of view but Autolayout was putting it back. 我试图改变视图的大小,但Autolayout正在把它放回去。 So I created outlet of my Height and Width constraint and changed it accordingly. 所以我创建了我的高度和宽度约束的出口并相应地改变了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM