I’m trying to add a UIColorWell into my storyboard, but it seems that you can’t drag and drop a UIColorWell in the same way that you can with other elements like a UITextField.
So, what I did was generate the UIColorWell from within my view controller’s .swift file.
Is there a way that I can attach the UIColorWell onto a UIView that I have drag and dropped into my storyboard?
Here is how I’ve tried to attach it, but when I run the simulator I don’t see the color well showing up anywhere on the screen.
class TagSelectionViewController: UIViewController {
var colorWell: UIColorWell!
@IBOutlet weak var UIViewForColorWell: UIView!
override func viewDidLoad() {
super.viewDidLoad()
addColorWell()
}
func addColorWell() {
colorWell = UIColorWell(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
self.view.addSubview(colorWell)
colorWell.center = UIViewForColorWell.center
colorWell.title = "Select Color"
colorWell.addTarget(self, action: #selector(colorWellChanged(_:)), for: .valueChanged)
}
@objc func colorWellChanged(_ sender: Any) {
self.view.backgroundColor = colorWell.selectedColor
}
}
2
Answers
This code is wrong:
In the first place, if you are going to add the color well to
self.view
, then you must position it with respect toself.view
. But you said you wanted to add it to UIViewForColorWell, so why did you not do that?Second, setting the subview
center
to the superviewcenter
is never right, because they are in two completely different coordinate systems; the way to center one view inside another is to use autolayout, or set its center to themidX
/midY
of the superview’s bounds.Finally, make sure the sizing on your UIViewForColorWell (terrible name) is good.
So I would say, try this:
As of Xcode 14, this is no longer a problem! You can now find
UIColorWell
in the interface builder.Old Answer:
Actually, you can add it to the storyboard. It’s just not in the list of views that you can choose from when you click the "+" button (maybe in the future?), so it’s the same way as you add any other custom view that you have written.
Add a regular
UIView
to the desired position of theUIColorWell
,go to the identity inspector and set the class to
UIColorWell
:You won’t actually see any change on the storyboard, but if you run the app, you will see the color well: