Search code examples
iosswiftcocoa-touchcolorsuislider

How to add members to UIView


So I'm trying to use this library in a project of mine: Color Slider and I'm following the instructions. It states that

self.colorSlider = ColorSlider()
self.colorSlider.frame = CGRectMake(0, 0, 10, 150)
self.view.addSubview(self.colorSlider)

is an appropriate way to add the colorSlider member. When I try this code, I get the error :

"[name of View Controller] does not have a member named colorSlider"

What exactly am I doing wrong and how would I go about fixing it? Thanks in advance!


Solution

  • you have to first declare the variable, something like this:

    var colorSlider = ColorSlider()
    

    I just added this to a project, and it works like butter when I first declare the variable, the view controller definitely finds it

    see the full viewController version:

    import UIKit
    
    class FirstViewController: UIViewController {
    
        var colorSlider: ColorSlider!
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
            colorSlider = ColorSlider(frame:CGRectMake(0, 0, 200, 150))
            view.addSubview(self.colorSlider)
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
    }
    

    If you want to test this, just make a new project in XCode, a swift project for a "Tabbed Application". Replace all the information in the FirstViewController with the last solution I've posted above, the solution right above this named "FirstViewController" and you can try it yourself!

    Okay, so with Storyboards:

    import UIKit
    
    class FirstViewController: UIViewController {
    
        @IBOutlet var colorSlider: ColorSlider!
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
    }
    

    And the setup, it looks like this:

    enter image description here

    So, this was a quick and simple typcasting of the UIView in the storyboard that supplies its view to the FirstViewController. As you can see, all I did was select the "View" of the "First Scene" and then in the "class" dropdown box, I just changed this from a UIView to a ColodSlider, this is basically a typecast with Storyboards. I don't use storyboards, ever, so the next best bet is to add another UIView to the "First Scene" and then resize it, once you have the size you want, then you just go to the class dropdown box again like I explained above and you select "ColorSlider" and you'll have a color slider in the view with the BIG VIEW, the main view, still being a UIView.