Joe Joe - 4 months ago 31
Swift Question

Cannot convert value of type int into Expected argument type 'CGfloat'

i'm trying to create subviews in my app programmatically, basically i'm a beginner in swift , while i trying to create 9 subview . I got an error "Cannot convert value of type 'int' into Expected argument type 'CGfloat'"
CGFloat values are A & B

import Foundation
import UIKit

@IBDesignable
class Subview: UIView {

@IBInspectable var view1 : UIView = UIView() {
didSet {

var A:CGFloat = 0
var B:CGFloat = 0
for A in 1...3 {
for B in 1...3 {
view1.frame = CGRectMake(A,B, 100, 100)

view1.backgroundColor = UIColor.blueColor()
self.addSubview(view1)

}
}

}
}


}

Answer

You overloaded A and B variables in cycles with same name but Int type variables (read more about for in cycle). You don't need to declare variables before use them as elements in for in, they are implicitly created in local cycle scope with type of elements of your collection (again, Int in your case). CGRectMake(_:_:_:_:) expect from you CGFloat's; and as @Martin R pointed you better use CGRect(x:y:width:height:). This code will solve conversion type problem:

didSet {
    for A in 1...3 {
        for B in 1...3 {
            view1.frame = CGRect(x: A, y: B, width: 100, height: 100)
            view1.backgroundColor = UIColor.blueColor()
            self.addSubview(view1)
        }
    }
}

But it have other, logic problems. Instance of UIView (view1) can be added only in one view hierarchy at same time. So, in fact, all code in your didSet will have just same result as this code:

didSet {
    view1.frame = CGRect(x: 3, y: 3, width: 100, height: 100)
    view1.backgroundColor = UIColor.blueColor()
    self.addSubview(view1)
}

Note also, that didSet observer not invoked on initialization step, so if you will not reassign view1 property this code will never be executed.

Comments