I'm building a weather app as a beginner project. Say I wanted a custom view that consisted on many UILabels for temp, humidity, precipitation, etc. The idea is that this custom UIView would be used several times for every city the user has saved. If the user has 3 cities saved, the custom view would have 3 instances.
What is the best way to do this? I'm trying to subclass a UIView. Originally I was overriding drawRect(rect: CGRect) and defining my UILabels there. That just didn't feel right. And it wouldn't get alloc/inited until way later, after I was trying to update the label text in the completion handler on NSURLSession.
Or should I be overriding init() which makes me do this:
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
And I have no idea what that means. Then I'm forced to doing something like this when I try to init with frame on the root VC.
override init(frame: CGRect) { super.init(frame: frame) }
Can someone walk me through the best approach? I have something like below but I get a nil value right when I'm trying to add the UILabels to subview of the custom class.
class ViewTemplate: UIView {
var tempLabel: UILabel!
var humidityLabel: UILabel!
override init () {
tempLabel = UILabel()
tempLabel.frame = CGRectMake(halfScreenWidth - 130, 120, 260, 130)
tempLabel.textColor = UIColor.whiteColor()
tempLabel.backgroundColor = UIColor.clearColor()
// similar stuff for humidityLabel
super.init()
addSubview(tempLabel)
}
override init(frame: CGRect) { super.init(frame: frame) }
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
If not quite sure where the nil is coming from. But most importantly, I'm looking for the best practice in doing this.
Thanks!
For creating the individual View:
Create new View file. Subclass of UIView. Be sure to also create the xib file when doing this.
Draw your items in storyboard (labels, etc.) and connect them to the swift file
Be certain that you connect them in storyboard by making the xib file a Custom Class of the swift file you just created.
Instantiate them inside the awakeFromNib() method. Be sure to set their default values for text if they are labels. Otherwise they will come up as nil when instantiated and your app will crash.
import UIKit
class MyView: UIView {
#IBOutlet weak var templabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.tempLabel.text = "95 degrees"
}
For loading into viewcontroller:
1a. Create a viewcontroller that implements UIScrollView.
1b. Place a UIScrollview in your storyboard and connect it to that viewcontroller
class MyWeatherViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet var scrollView: UIScrollView!
2a. In ViewDidLoad, create instances of the UIView you are looking to create. Populate them individually.
2b. In ViewDidLoad, set the scrollview width to the width of a single View. Set the height to the height of the single View * the number of Views you wish to display
var view1: MyView = MyView()
var view2: MyView = MyView()
let viewArray[MyView!] = [view1, view2]
for items in viewArray {
var frame = scrollView.bounds
//Set the origin of the views
frame.origin.x = 0.0
frame.origin.y = frame.size.height * items
//create a view out of the object provided, define it's frame, and add to scrollview
let viewToAdd = viewArray[items].view
newPageView.frame = frame
scrollView.addSubview(viewToAdd)
//Set up your labels to be displayed. You must do this AFTER you load the load into the scrollview
viewArray[items].tempLabel.text = "105 degrees"
}
Keep in mind that you will want to set up another data model to hold the information that is to be displayed. I would recommend creating an array that holds the information you wish to display, so you can do viewArray[items].tempLabel.text = tempArray[items] with all the labels you wish to set.
This should align them vertically with the ability to scroll and see all items.
This will also let dynamically decide how many views to add based on cities the user has saved. Just modify the logic to read however many cities the user has etc.
You're on the right track.
Declare the properties for the labels. It looks like you've already done that. Personally, I would declare those as constants with let instead of var because you should always have those labels.
Override the init(frame: CGRect) method. Again, it looks like you've already started this. The reason you should override init(frame: CGRect) instead if init() is because init() just calls init(frame: CGRectZero). If you only implement init() then some of your properties may not get initialized (although this is way less of an issue with Swift since you can declare properties as constants so the compiler throws an error). In your initializer you're going to want to init all your labels & set them up right before you call super.init(frame). After the super.init(frame) method is called you should add the labels as subviews of self.
Override layoutSubviews() if you are laying your UI out programmatically. This method is where you will do all the sizing and laying out of your subviews. I do everything this way so it's what I'm most familiar with. If you're using AutoLayout I believe it's best practice to apply those constraints in the class's initializer since they should only ever need to be set up once.
Optionally, you may also want to override sizeThatFits(). This will ensure your view is always the proper size when sizeToFit() is called on it.
This goes not just for UIView but any subclass of it.
You can use a UIViewController extension and initialize a UIView function that takes a UIView. You can use this anywhere in your project.
extension UIViewController {
func setView(_ view: UIView){
view.backgroundColor = UIColor()
view.layer.cornerRadius = 5.0
// customize your view
}
}
Then: Declare you view in your Controller and pass it when the function is called on viewDidLoad()
let myView = UIView()
setView(myView)
Related
Let's say I have SomeViewController: UIViewController, and I have a custom view CustomView: UIView, defined as a XIB, that I want to display. This custom view will be reused in other view controllers and even multiple times in the same view controller.
class CustomView: UIView {
#IBOutlet public var label: UILabel!
}
The way I have always added this view has been:
class UIExamples: UIViewController {
#IBOutlet private var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Assume makeViewFromNib returns the view [0] in the Nib.
let customView = makeViewFromNib(nib: "\(CustomView.self)", owner: self) as! CustomView
customView.frame = myView.bounds
myView.addSubview(customView)
}
}
Let's say that later on I want to modify something about the CustomView via a public property label.
I could do it inside viewDidLoad ONLY BECAUSE I have access to customView, but what if I want to change it in some other function? What I have seen is that one would have to do
let customView = myView.subviews[0] as! CustomView
customView.label.text = "some text"
which does not look right.
So, I thought the right way should be this:
class UIExamples: UIViewController {
#IBOutlet public var customView: CustomView! // Now this is always a CustomView type
override func viewDidLoad() {
super.viewDidLoad()
// Assume makeViewFromNib returns the view [0] in the Nib.
customView = makeViewFromNib(nib: "\(CustomView.self)", owner: self) as! CustomView
customView.label.text = "some text" // DOES NOT WORK!
}
}
That last line customView.label.text does not work. In fact, the label is not even seen on the screen. What am I doing wrong?
OK, didn't read (or maybe was reading before edit) that you use xib. If ViewController is created from xib with label in it this will be correct way:
set myView class in xib here:
and then connect IBOutlet (remove current one from xib here:
and then from code).
Now myView.label.text = "some text" should work without further issues.
Good luck!
If you create your view from code do it in this manner:
class UIExamples: UIViewController {
#IBOutlet private var myView: CustomView!
override func viewDidLoad() {
super.viewDidLoad()
// Assume makeViewFromNib returns the view [0] in the Nib.
myView = makeViewFromNib(nib: "\(CustomView.self)", owner: self) as! CustomView
myView.frame = view.bounds
view.addSubview(myView)
}
}
Because you already have property storing this view in your view controller it's unnecessary to dig inside subviews, it will work like that
myView.label.text = "some text"
And reason for
customView = makeViewFromNib(nib: "\(CustomView.self)", owner: self) as! CustomView
customView.label.text = "some text"
isn't working is because it's completely new view that wasn't added to your view controller subviews (also frame wasn't set BTW). And because you changed value of your customView property it's now not pointing to old instance of view, that is present in subviews (you can still see that "old one" but not change it).
But I really recommend to use pointer created once, as correct class to avoid casting. (Or creating view directly in xib / storyboard, otherwise #IBOutlet is not necessary)
Posting my own answer.
Create the XIB file.
Create the UIView subclass Swift file.
Under the XIB file owner's Identify Inspector custom class field, type in the UIView subclass name (your custom view).
Under the XIB file owner's Connections Inspector, make sure all IBOutlets in the Swift file are connected.
Add a view to the view controller and under its Identify Inspector custom class type, specify the custom class name.
Important:
* In your XIB swift file, you have to properly load the XIB content view.
...
/// Initializer used by Interface Builder.
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
/// Initializer used programmatically.
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
...
func configure() {
let contentView = // here use many of the functions available on the internet to
// load a view from a nib.
// Then add this view to the view hierarchy.
addSubview(contentView)
}
I have a UIView class. And assigned it to a UIView inside of a ViewController.
I am animating the drawing of a circle in the UIView.
How do I load the UIView in the ViewController?
ViewDidLoad doesn’t work or gives errors.
LoadView also doesn’t work.
Create class for your view controller lets say ParentController subclass of UIViewController.
Create outlet of your UIView in ParentController.
Instead of creating class for UIView define function in ParentController to draw circle and call it in ParentController.
After function call show your add your UIView to ParentController
e.g - self.view.addSubview(self.cirecleUIview)
I personally suggest
1) create a file for your class, say MyView.
2) create a NIB/XIB, too, so you can eventually add other elements.
3) add a custom element (of class MyView) in controller in Main storyboard
4) Add outlet in your controller to your view (so you can fill/set/access it..)
5) NEVER call directly drawing functions (will be automatic.. or triggered manually using setNeedsUpdate..)
6) override init/awake methods, so you can load from resources or code:
override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
final private func prepare(){
// your "init" code here..
}
6) implement you drawing code:
override func draw(_ rect: CGRect) {
// stupid code.. will fill in red...
if let context = UIGraphicsGetCurrentContext(){
context.setFillColor(UIColor.red.cgColor)
context.addRect(rect)
context.fillPath()
}
}
Im building my views programatically, but need to refer to the views in my controller for setting properties. I cant see a way to achieve this?
I have a reference to the view as of course the controller inits it, but then i cant access properties for example trying self.view.textField as id thought i would.
How do I achieve this? And vice versa how do I do things like setting the views textField to use the controller as its delegate to handle its input?
First time ive not used storyboard where all this was simpler but messier, appreciate any clarification on these issues
It's easy.
Initialize your UI elements directly in UIViewController.
For example:
private let yourLabel: UILabel = {
let label = UILabel()
label.text = "Text"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
private func setupViews() {
view.addSubview(yourLabel)
// Setup constraints for yourLabel
}
Then access yourLabel anywhere in the controller code. It works for all the UI components.
NOTE!
You can setup all the views not in the controller, but in a separate view. And then add only one view (with other subviews inside) to the controller. You will have access to all subviews using this one view. But the way how you create UI components in the separate view will be the same:
let yourSubView: UILabel = { // any UI component
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
Example of a custom separate UIView:
class CustomView: UIView { // Separate view. Doesn't make the controller massive
let yourSubView: UILabel = { // any UI component
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setupViews() {
addSubview(yourSubView)
// Setup yourSubView constraints
}
}
Then you can add CustomView to UIViewController and access all the subviews of CustomView.
I have a UITableViewController with a list of custom UITableViewCells. The cell has text, which is sometimes long. I am truncating that at 2 lines in the table.
When a user touches the cell, I want to create a UIView as a popup with the exact same information as the UITableViewCell, with the addition of a header above the UITableViewCell content. So, essentially, I want something like the following:
I have built VersePopupView just as indicated in the picture, where the text "Custom Header" is actually a UILabel. I have instantiated the view from the XIB file and successfully set the UILabel text, but the custom UITableViewCell doesn't show, even though I have assigned that value as well. My IBOutlets are all hooked up to IB.
Here is my instantiation:
let popupView: VersePopupView = VersePopupView.instanceFromNib()
popupView.frame = CGRect(x: 10, y: 100, width: 300, height: 100)
popupView.assignVerseTableViewCell(cell: cell)
window.addSubview(popupView)
window.makeKeyAndVisible()
And here is my VersePopupView class:
class VersePopupView: UIView {
#IBOutlet weak var cell: VerseTableViewCell!
#IBOutlet weak var title: UILabel!
#IBOutlet weak var headerView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
class func instanceFromNib() -> VersePopupView {
return UINib(nibName: "VersePopupView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! VersePopupView
}
func assignVerseTableViewCell(cell: VerseTableViewCell)
{
// Assign it
self.cell = cell
// Get the verse details
if let verseDetails = cell.verse_details {
self.title.text = verseDetails.verseReference()
// Adjust the frame
// Adjust the text to be attributed text
// Set the title to the verse reference
// Anything else?
}
}
}
What am I doing wrong such that the UITableViewCell isn't showing up?
Is there a better pattern for this rather than embedding the UITableViewCell?
I don't want to duplicate code (which I have done in the past), because I want the user to interact with the popup just like they would in the table cell.
I'm not sure how to convince you of how easy this is to do without trying to misuse a table view cell, so here's a screen shot:
You just have to believe me when I say that that's a three-row table followed by a totally independent ordinary view plucked from the inside of the table view cell (by loading the cell nib).
They not only look identical, they act identical; the view is a custom UIView subclass with an action method from the switch, and when I click the switch, it triggers that action method, both within the table and in the view outside it.
The view was designed entirely in the nib, and absolutely no code was repeated.
That seems to be the sort of thing you want to do. So, I encourage you, don't misuse table view cells; do this with an ordinary view that can live happily inside a cell or outside it.
I have some weird behavior related to frame sizes that I can't fix after hours of trying different things. This just doesn't make any sense.
I have a custom UIView and a related .xib file:
ErrorView.swift
import UIKit
class ErrorView: UIView {
#IBOutlet weak var labelErrorTitle: UILabel!
#IBOutlet weak var view: UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
func setupView() {
NSBundle.mainBundle().loadNibNamed("ErrorView", owner: self, options: nil)
self.addSubview(view)
}
ErrorView.xib (using inferred size, the label is centered using constraints)
I want to add this view to a custom UITableView, at the bottom. I want to make it slim, with a height of 45 and a width of the view screen width. I want to add it to the bottom.
Very easy!! I just set the size with a frame like this:
class LoadingTableView: UITableView {
var errorView: ErrorView = ErrorView () // Here is the Error View
var errorFrame: CGRect! // The frame (size) I will use
required init(coder aDecoder: NSCoder) {
}
override func awakeFromNib() {
super.awakeFromNib()
// I create the frame here to put the error at the top
errorFrame = CGRectMake(0,0,self.frame.width,45)
// Init the ErrorView
errorView = ErrorView(frame: errorFrame)
// I add the subview to root (I have this rootView created)
rootView?.addSubview(errorView)
}
// This is needed, it updates the size when layout changes
override func layoutSubviews() {
super.layoutSubviews()
// Create the size again
errorFrame = CGRectMake(0,0,self.frame.width,45)
// I update the frame
errorView.frame = frame
}
This should work but it doesn't. The size is just weird. It takes the size from the nib which is 320x568. Then it just moves the frame, but the size doesn't change.
And here comes the great part. If I set the errorView.frame size to .frame, which is the frame of the tableView then it works! With orientation changes and all!
But as long as I change the frame to a custom size, whatever is in awakeFromNib or layoutSubviews it doesn't and starts to act weird.
Why does it keeps the size of the nib? And why if I put .frame it works at it should but a custom size doesn't? It looks like I'm super close, it's frustrating as hell.
The objective is to say tableView.error("errorCode") and then that errorView appears. And it works on all devices and orientations.
Instead of adding a subview to UITableView, use it's tableFooterView and tableHeaderView properties:
Replace
rootView?.addSubview(errorView)
With:
tableFooterView = errorView