Reputation: 342
I am simply trying to set two var to the bounds.size.width and .height of a view.
import UIKit
class BKView: UIView {
var maxX: CGFloat = bounds.size.width
var maxY: CGFloat = bounds.size.height
}
However Xcode fails saying with error: 'BKView.Type' does not have member named 'bounds'.
Any suggestions?
Upvotes: 1
Views: 1537
Reputation: 2778
When creating a view, It is needed to define some default initialiser methods. Define a class as follows:
class TestView: UIView {
var maxX : CGFloat?
var maxY : CGFloat?
override init() {
super.init()
initializeBounds()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeBounds()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeBounds()
}
func initializeBounds()
{
maxX = self.bounds.size.width
maxY = self.bounds.size.height
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
println("maxX: \(maxX!) maxY: \(maxY!)")
}
}
Whenever the TestView
is initialised by Storyboard or Coding, the TestView
's properties getting initialised.
After adding the view to your view controller's view as follows:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var testView : TestView = TestView(frame: CGRectMake(10.0, 10.0, 100.0, 50.0))
testView.backgroundColor = UIColor.redColor()
self.view.addSubview(testView)
}
The log gives as follows:
TestView: maxX: 100.0 maxY: 50.0
To avoid replication of code, initializeBounds()
is defined and called in TestView
's initializers:
Upvotes: 1
Reputation: 22939
@Airspeed Velocity gives a good explanation. I wanted to add that alternatively you could use lazy
initialisation. For example:
class BKView: UIView {
lazy var maxX: CGFloat = self.bounds.size.width
lazy var maxY: CGFloat = self.bounds.size.height
}
For more information see: http://mikebuss.com/2014/06/22/lazy-initialization-swift/
Upvotes: 2
Reputation: 12324
Use self.bounds.size.width
and self.bounds.size.height
. You should assign the properties maxX
and maxY
values in an initializer or some other function, instead of inline. Example:
init(frame: CGRect) {
super.init(frame: frame)
maxX = self.bounds.size.width
maxY = self.bounds.size.height
}
Upvotes: 0
Reputation: 40955
It's a terribly-worded compiler error, but what it means is that you can't give properties default values based on other properties of the class (or superclass). Here's a simpler variant of what's happening:
class A {
let x: Int
init(x: Int) {
self.x = x
}
}
class B: A {
// error: 'B.Type' does not have a member named 'x'
let y = x
}
You'll have to initialize maxX
and maxY
inside an init
method instead, after you've called super.init
(because only after that are you allowed to access the superclass's properties).
Upvotes: 4