Tutorials

Tutorials about HTML, CSS, PHP, Javascript, and Photoshop

  • Home
    Home This is where you can find all the blog posts throughout the site.
  • Categories
    Categories Displays a list of categories from this blog.
  • Tags
    Tags Displays a list of tags that has been used in the blog.
  • Archives
    Archives Contains a list of blog posts that were created previously.
  • Login
5233

We continue our exploration of the , In this tutorialNSFetchedResultsControllerClass by adding the ability to update and delete to-do items. You'll notice that updating and deleting to-do items is surprisingly easy thanks to the groundwork we laid in theprevious tutorial

1. Updating a Record's Name

Step 1: Create View Controller

Start by creating a newUIViewControllerSubclass named TSPUpdateToDoViewControllerIn TSPUpdateToDoViewController. HDeclare an outletTextFieldOf typeUITextFieldAnd two propertiesManagedObjectContextOf typeNSManagedObjectContextAnd RecordOf type NSManagedObjectAdd an import statement for the Core Data framework at the top

#import <UIKit/UIKit. H>

#import <CoreData/CoreData. Nonatomic) NSManagedObjectContext *managedObjectContext;

@property (strong, nonatomic) NSManagedObject *record;

@end, h>

@interface TSPUpdateToDoViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *textField;

@property (strong

In the view controller's implementation file,  TSPUpdateToDoViewController. MCreate two actionsCancel:AndSave:Their implementations can remain empty for the time being

#import "TSPUpdateToDoViewController.h"

@implementation TSPUpdateToDoViewController

#pragma mark -
#pragma mark Actions
- (IBAction)cancel:(id)sender{
    
}- (IBAction)save:(id)sender{
    
}@end

Step 2: Update Storyboard

 , Open the main storyboardMain. StoryboardAdd a new view controller object, and set its class toTSPUpdateToDoViewControllerIn theIdentity InspectorCreate a manual segue from theTSPViewControllerClass to theTSPUpdateToDoViewControllerClass. In the Attributes InspectorSet the segue's style toPush and its identifier to UpdateToDoViewController

Add aUITextFieldObject to the view of the TSPUpdateToDoViewControllerObject and configure it just like we did with the text field of the TSPAddToDoViewControllerClass. Don't forget to connect the view controller's outlet with the text field

As in the TSPAddToDoViewControllerClass, add two bar button items to the view controller's navigation bar, set their identities to CancelAnd SaveRespectively, and connect each bar button item to the corresponding action in the Connections Inspector

Step 3: Passing a Reference

We also need to make a few changes to the TSPViewControllerClass.  Add an import statement for the TSPUpdateToDoViewController class at the top and declare a property named SelectionOf typeNSIndexPathTo the private class extension inTSPViewController. M

#import "TSPViewController.h"

#import <CoreData/CoreData. H>

#import "TSPToDoCell.h"
#import "TSPAddToDoViewController.h"
#import "TSPUpdateToDoViewController.h"

@interface TSPViewController () <NSFetchedResultsControllerDelegate>

@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;

@property (strong, nonatomic) NSIndexPath *selection;

@end

Next, implement theTableView:didSelectRowAtIndexPath:Method of theUITableViewDelegateProtocol. We temporarily store the user's selection in the , In this methodSelection property

#pragma mark -
#pragma mark Table View Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // Store Selection
    [self setSelection:indexPath];
}

In the class's PrepareForSegue:sender:We fetch the record that corresponds with the user's selection and pass it to the TSPUpdateToDoViewControllerInstance. To prevent any unexpected behavior, we only perform this step if selection isn't Nil and reset theSelectionProperty after fetching the record from the fetched results controller

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue. Identifier isEqualToString:@"addToDoViewController"]) {
        // Obtain Reference to View Controller
        UINavigationController *nc = (UINavigationController *)[segue destinationViewController];
        TSPAddToDoViewController *vc = (TSPAddToDoViewController *)[nc topViewController];
        
        // Configure View Controller
        [vc setManagedObjectContext:self. ManagedObjectContext];
        
    }Else if ([segue. Identifier isEqualToString:@"updateToDoViewController"]) {
        // Obtain Reference to View Controller
        TSPUpdateToDoViewController *vc = (TSPUpdateToDoViewController *)[segue destinationViewController];
        
        // Configure View Controller
        [vc setManagedObjectContext:self. ManagedObjectContext];
        
        if (self. Selection) {
            // Fetch Record
            NSManagedObject *record = [self. FetchedResultsController objectAtIndexPath:self. Selection];
            
            if (record) {
                [vc setRecord:record];
            }// Reset Selection
            [self setSelection:nil];
        }
    }
}

Step 4: Populating the Text Field

In theViewDidLoadMethod of the TSPUpdateToDoViewControllerPopulate the text field with the name of the record as shown below, class

#pragma mark -
#pragma mark View Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self. Record) {
        // Update Text Field
        [self. TextField setText:[self. Record valueForKey:@"name"]];
    }
}

Step 5: Updating the Record

In theCancel:Action, we pop the update view controller from the navigation controller's navigation stack

- (IBAction)cancel:(id)sender {
    // Pop View Controller
    [self. NavigationController popViewControllerAnimated:YES];
}

In theSave:Action, we first check if the text field is empty and show an alert view if it is. We update the record's, If the text field contains a valid valueNameAttribute and pop the view controller from the navigation controller's navigation stack

- (IBAction)save:(id)sender {
    // Helpers
    NSString *name = self. TextField. Text;
    
    if (name && name. Length) {
        // Populate Record
        [self. Record setValue:name forKey:@"name"];
        
        // Save Record
        NSError *error = nil;
        
        if ([self. ManagedObjectContext save:&error]) {
            // Pop View Controller
            [self. NavigationController popViewControllerAnimated:YES];
            
        }Error, else {
            if (error) {
                NSLog(@"Unable to save record.");
                NSLog(@"%@, %@", error. LocalizedDescription);
            }// Show Alert View
            [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your to-do could not be saved." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }
        
    }Else {
        // Show Alert View
        [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your to-do needs a name." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    }
}

This is all it takes to update a record using Core Data.  Run the application once more and see if everything is working. The , The fetched results controller automatically detects the change and notifies its delegateTSPViewControllerInstance. TheTSPViewController updates the table view to reflect the change, on its turn, object. It's that easy

2. Updating a Record's State

Step 1: Updating TSPToDoCell

When a user taps the button on the right of aTSPToDoCellThe item's state needs to change. To accomplish this, we first need to update theTSPToDoCellClass. Open TSPToDoCell. MAnd add aTypedefFor a block named TSPToDoCellDidTapButtonBlockNext, declare a property of type TSPToDoCellDidTapButtonBlockAnd make sure the property is copied on assignment

#import <UIKit/UIKit. H>

typedef void (^TSPToDoCellDidTapButtonBlock)();

@interface TSPToDoCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIButton *doneButton;

@property (copy, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) TSPToDoCellDidTapButtonBlock didTapButtonBlock;

@end

 , Head to the class's implementation fileTSPToDoCell. MAnd invokeSetupViewA helper method, inAwakeFromNib

#pragma mark -
#pragma mark Initialization
- (void)awakeFromNib {
    [super awakeFromNib];
    
    // Setup View
    [self setupView];
}

InSetupViewWe configure theDoneButtonObject by setting images for each state of the button and adding the table view cell as a target. When the user taps the button, the table view cell is sent a message ofDidTapButton:In which we invoke theDidTapButtonBlockBlock. You'll see in a moment how convenient this pattern is. The images are included in thesource filesOf this tutorial, which you can find onGitHub

#pragma mark -
#pragma mark View Methods
- (void)setupView {
    UIImage *imageNormal = [UIImage imageNamed:@"button-done-normal"];
    UIImage *imageSelected = [UIImage imageNamed:@"button-done-selected"];
    
    [self. DoneButton setImage:imageNormal forState:UIControlStateNormal];
    [self. DoneButton setImage:imageNormal forState:UIControlStateDisabled];
    [self. DoneButton setImage:imageSelected forState:UIControlStateSelected];
    [self. DoneButton setImage:imageSelected forState:UIControlStateHighlighted];
    [self. DoneButton addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark -
#pragma mark Actions
- (void)didTapButton:(UIButton *)button {
    if (self. DidTapButtonBlock) {
        self. DidTapButtonBlock();
    }
}

Step 2: Updating TSPViewController

Thanks to the NSFetchedResultsControllerClass and the foundation we've laid, we only need to update the ConfigureCell:atIndexPath:Method in the TSPViewControllerClass

- (void)configureCell:(TSPToDoCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // Fetch Record
    NSManagedObject *record = [self. FetchedResultsController objectAtIndexPath:indexPath];
    
    // Update Cell
    [cell. NameLabel setText:[record valueForKey:@"name"]];
    [cell. DoneButton setSelected:[[record valueForKey:@"done"] boolValue]];
    
    [cell setDidTapButtonBlock:^{
        BOOL isDone = [[record valueForKey:@"done"] boolValue];
        
        // Update Record
        [record setValue:@(. IsDone) forKey:@"done"];
    }];
}

Step 3: Saving Changes

You may be wondering why we aren't saving the managed object context. Won't we lose the changes we've made if we don't commit the changes to the persistent store. Yes and no

It is true that we need to write the changes of the managed object context to the backing store at some point. If we don't, the user will lose some of its data. There is no need to save the changes of a managed object context every time we make a change, However

A better approach is to save the managed object context the moment the application moves to the background. We can do this in the ApplicationDidEnterBackground:Method of the UIApplicationDelegate protocol.  OpenTSPAppDelegate. MAnd implement ApplicationDidEnterBackground:As shown below

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSError *error = nil;
    
    if (. [self. Error, error, managedObjectContext save:&error]) {
        if (error) {
            NSLog(@"Unable to save changes.");
            NSLog(@"%@, %@". LocalizedDescription);
        }
    }
}

This doesn't work if the application is force quit by the user, However. It's therefore a good idea to also save the managed object context when the application is terminated. The ApplicationWillTerminate:Method is another method of theUIApplicationDelegateProtocol that notifies the application't delegate when the application is about to be

- (void)applicationWillTerminate:(UIApplication *)application {
    NSError *error = nil;
    
    if (. [self. Error, error, managedObjectContext save:&error]) {
        if (error) {
            NSLog(@"Unable to save changes.");
            NSLog(@"%@, %@". LocalizedDescription);
        }
    }
}

Note that we have duplicate code inApplicationDidEnterBackground:And ApplicationWillTerminate:It's therefore a good idea to create a helper method to save the managed object context and call this helper method in both delegate methods

#pragma mark -
#pragma mark Helper Methods
- (void)saveManagedObjectContext {
    NSError *error = nil;
    
    if (. [self. Error, error, managedObjectContext save:&error]) {
        if (error) {
            NSLog(@"Unable to save changes.");
            NSLog(@"%@, %@". LocalizedDescription);
        }
    }
}

3. Deleting Records

You'll be surprised by how easy it is to delete records using the NSFetchedResultsControllerClass. Start by implementing the TableView:canEditRowAtIndexPath:Method of theUITableViewDataSourceProtocol

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

The second method of the UITableViewDataSource protocol that we need to implement isTableView:commitEditingStyle:forRowAtIndexPath:In this method we fetch the managed object the user has selected for deletion and pass it to theDeleteObject:Method of the managed object context of the fetched results controller

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSManagedObject *record = [self. FetchedResultsController objectAtIndexPath:indexPath];
        
        if (record) {
            [self. FetchedResultsController. ManagedObjectContext deleteObject:record];
        }
    }
}

Because we've already implemented the NSFetchedResultsControllerDelegateThe user interface is automatically updated, protocol, animations included

Conclusion

I hope you agree that the NSFetchedResultsControllerClass is a very convenient member of the Core Data framework. If you understand the basics of the Core Data framework, then it's not difficult to get up to speed with this class. I encourage you to further explore theits API to find out what else it can do for you

Continue reading
0
5832

When your profession involves writing code for significantly long periods of time, even deceptively trivial things such the font you’re using can make a huge difference.

This is a list of fonts for people who love code.

For your convenience, I have created a sample page for all the fonts mentioned here, which may help you choose the one that’s right for you.

Programming Fonts Sample Page

View source on GitHub

Selection Criteria

Here are the factors used for choosing the fonts in this list.

Monospaced

A good font that’s used for programming should be monospaced, meaning each character occupies the same amount of horizontal space1. Monospaced fonts are also called fixed-width fonts.

Using a fixed-width font is essential for formatting and readability of source code.

Screen readability and legibility

When you have to stare at code for hours, reading comfort is really important.

In addition, research shows that fonts can affect the user experience; typography has measurable cognitive effects on our mood2, which, in turn, could have indirect implications towards our productivity.

Preferably, the font we choose is explicitly designed with coding in mind, and is optimized especially for on-screen/computer-monitor readability.

Readability is a subjective matter — what’s easy for me to read, might not be so for you. The programming fonts sample page can be used as a rudimentary tool for evaluating the readability and legibility of each font in this list.

Unambiguous characters

To avoid syntax errors, we should be able to effortlessly distinguish between similar characters such as l, 1, | and I when we’re writing/reading code. Programmers shouldn’t have to wonder whether they typed 0, O or o, or whether a string value is wrapped with backticks (``) or apostrophes ('').

The sample page has a code block that contains potentially ambiguous characters so that you are able to test a particular font’s legibility.

Truly free

The best programming fonts are free and open-sourced in my opinion. And, particularly for those of us who are web developers, we’d like to not have to worry about whether or not we can render the font in the browser as part of a UI design.

My intention with this list is to highlight free fonts that are truly free. Some popular programming fonts — fonts that I also personally love, such as Consolas and Monaco — were intentionally left out because their licensing terms outside of personal use were unclear.

Reputation

A great deal of time was spent hunting down and researching the fonts for inclusion in this list. This activity led me to fonts that are well-loved by the programming community and helped me narrow this roundup down to a manageable size.

Personal preference

There’s always going to be some level of bias when pulling together a list like this.

There are many excellent programming fonts out there that match the criteria above, but at the end of the day this list has a major flaw and limiting factor: Me. I chose to include only the programming fonts I’m comfortable recommending to others. If you have recommendations, please share them in the comments section of this article.

The Fonts

You’ll find a table listing relevant resources and information for each font. Also, each font has multiple download links pointing to trustworthy domains in case a link stops working in the future.

1. Anonymous Pro

Anonymous Pro, by typeface designer Mark Simonson, was "designed especially for coders," according to its website. This font has keyboard characters like the Command key found on Apple keyboards, making it a good candidate font for displaying keyboard shortcuts on web pages and user interfaces.

Anonymous Pro resources
Official site Anonymous Pro
Useful resources Anonymous Pro specimen (PDF) (Mark Simonson)
Anonymous Pro: a programming font with style (Hivelogic)
Sites using Anonymous Pro (Typewolf)
License SIL Open Font License
Download links Mark Simonson
Font Squirrel
Google Fonts

2. Cousine

If you’re a fan of the Courier font family, then you’re going to like Cousine. Cousine improves on the font family that inspired it by offering "improved on-screen readability characteristics"3. This font was made by Steve Matteson, the designer of many of the fonts you see in open source operating systems.

Cousine resources
More info Cousine (Open Font Library)
License Apache License version 2.0
Download links Font Squirrel
Google Fonts

3. DejaVu Sans Mono

This monospaced font is a member of the DejaVu font family, an open source project. The font’s characters are markedly more robust compared to others in the same class.

DejaVu Sans Mono resources
Official site DejaVu Fonts
Useful resources DejaVu font specimen (PDF) (DejaVu Fonts)
Repo SourceForge.net
License Free license (custom)
Download links DejaVu Fonts
Font Squirrel

4. Droid Sans Mono

Part of the Droid font family, and commissioned by Google, this monospaced member promises "excellent legibility characteristics in its letterforms," according to its official description. This font functions well in code editors, but also looks good when rendered in user interfaces. Droid Sans Mono is also by Steve Matteson.

Droid Sans Mono resources
Official site Droid Sans Mono
Useful resources Droid Sans Mono great coding font (DamienG)
Font sample Droid Sans Mono (Wikipedia)
Repo GitHub
License Apache License version 2.0
Download links Font Squirrel
Google Fonts

5. Fira Mono

The Fira font family, designed by Erik Spiekermann, was commissioned by Mozilla for their OS. This monospaced variant has excellent punctuation-mark legibility for me.

Fira Mono resources
Official site Fira Sans on the designer’s website
Useful resources Mozilla Style Guide: Firefox OS Typeface (Mozilla)
Fira specimen page (Mozilla/Github.io)
Repo GitHub
License SIL Open Font License
Download links Carrois
Font Squirrel
Google Fonts

6. Hermit

Hermit is "a font for programmers, by a programmer." This font is a relatively new font. It’s by Pablo Caro, whose professional background as an engineer and computer scientist, and track record of projects, make him an individual not only qualified to know what the needs of programmers are, but also an interestingly atypical designer of fonts. This monospaced font is "designed to be clear, pragmatic and very readable," according to Caro’s website. "Its creation has been focused on programming."

Hermit resources
Official site Hermit
Repo GitHub
License SIL Open Font License
Download links Pablo Caro
GitHub

7. Inconsolata

Inconsolata draws inspiration from the ubiquitous Consolas font by Microsoft. Inconsolata was developed by Raph Levien, a Google engineer currently assigned to the Android platform. Levien says on his site that though there are many great programming fonts, many of them "do not have the attention to detail for high resolution rendering."

Inconsolata resources
Official site Inconsolata
License SIL Open Font License
Download links Levien.com
Font Squirrel
Google Fonts

8. Oxygen Mono

This monospaced font family is by Vernon Adams, a person who’s well-known in the open source font community. Oxygen Mono works well on the desktop. The font’s characters — and particularly, for me, its punctionation marks — have great definition and legibility.

Oxygen Mono resources
More info Oxygen Mono (Google Fonts)
Useful resources Very first drafts of ‘Oxygen Monospace’ (NewTypography)
Repo GitHub
License SIL Open Font License
Download links Font Squirrel
Google Fonts

9. PT Mono

The PT font family was designed for the Russian language, but works equally well with the Latin alphabet. The PT Mono variation is by Alexandra Korolkova. The font’s very readable, as well as very elegant with its Humanist characteristics.

PT Mono resources
Official site ParaType Public Types Project
License SIL Open Font License
Download links ParaType
Font Squirrel
Google Fonts

10. Source Code Pro

Source Code Pro created by Paul D. Hunt. This font is one of Adobe’s open source projects. Source Code Pro is comfortable to read and write code with.

Source Code Pro resources
Official site Source Code Pro
Repo GitHub
License SIL Open Font License
Download links Font Squirrel
Google Fonts

11. Luculent

Luculent is a font family designed for programmers. Several styles are included, which can help with syntax highlighting. Its development started in 2008, but it has only been recently released.

Luculent resources
Official site Luculent
License SIL Open Font License (OFL)
Download links Official Site


12. M+

M+ is a huge font family designed for the Japanese character set. Its fixed-width latin character variation is well-loved by many programmers.

M+ resources
Official site M+
Repo SourceForge Japan
License Custom free license
Download links Official site


13. Ubuntu Mono

The Ubuntu Font family was designed by Dalton Maag, a top font foundry. Its monospaced font is very clear and legible, and perfect for extended coding sessions.

Ubuntu Mono resources
Official site Unbuntu Font Family
License Ubuntu Font Licence
Download links Official site
Font Squirrel
Google Fonts

References

  1. Monospaced font (wikipedia.org)
  2. The Aesthetics of Reading (PDF) (mit.edu)
  3. Google Fonts Cousine (google.com)

Related Content

About the Author

Jacob Gube is the founder of Six Revisions. He’s a front-end web developer by profession. If you’d like to connect with him, head on over to the contact page or follow him on Twitter: @sixrevisions.

The post Free Programming Fonts appeared first on Six Revisions.

Continue reading
0
22744

When your profession involves writing code for significantly long periods of time, even deceptively trivial things such the font you’re using can make a huge difference.

This is a list of fonts for people who love code.

For your convenience, I have created a sample page for all the fonts mentioned here, which may help you choose the one that’s right for you.

Programming Fonts Sample Page

View source on GitHub

Selection Criteria

Here are the factors used for choosing the fonts in this list.

Monospaced

A good font that’s used for programming should be monospaced, meaning each character occupies the same amount of horizontal space1. Monospaced fonts are also called fixed-width fonts.

Using a fixed-width font is essential for formatting and readability of source code.

Screen readability and legibility

When you have to stare at code for hours, reading comfort is really important.

In addition, research shows that fonts can affect the user experience; typography has measurable cognitive effects on our mood2, which, in turn, could have indirect implications towards our productivity.

Preferably, the font we choose is explicitly designed with coding in mind, and is optimized especially for on-screen/computer-monitor readability.

Readability is a subjective matter — what’s easy for me to read, might not be so for you. The programming fonts sample page can be used as a rudimentary tool for evaluating the readability and legibility of each font in this list.

Unambiguous characters

To avoid syntax errors, we should be able to effortlessly distinguish between similar characters such as l, 1, | and I when we’re writing/reading code. Programmers shouldn’t have to wonder whether they typed 0, O or o, or whether a string value is wrapped with backticks (``) or apostrophes ('').

The sample page has a code block that contains potentially ambiguous characters so that you are able to test a particular font’s legibility.

Truly free

The best programming fonts are free and open-sourced in my opinion. And, particularly for those of us who are web developers, we’d like to not have to worry about whether or not we can render the font in the browser as part of a UI design.

My intention with this list is to highlight free fonts that are truly free. Some popular programming fonts — fonts that I also personally love, such as Consolas and Monaco — were intentionally left out because their licensing terms outside of personal use were unclear.

Reputation

A great deal of time was spent hunting down and researching the fonts for inclusion in this list. This activity led me to fonts that are well-loved by the programming community and helped me narrow this roundup down to a manageable size.

Personal preference

There’s always going to be some level of bias when pulling together a list like this.

There are many excellent programming fonts out there that match the criteria above, but at the end of the day this list has a major flaw and limiting factor: Me. I chose to include only the programming fonts I’m comfortable recommending to others. If you have recommendations, please share them in the comments section of this article.

The Fonts

You’ll find a table listing relevant resources and information for each font. Also, each font has multiple download links pointing to trustworthy domains in case a link stops working in the future.

Here are the ten free programming fonts.

1. Anonymous Pro

Anonymous Pro, by typeface designer Mark Simonson, was "designed especially for coders," according to its website. This font has keyboard characters like the Command key found on Apple keyboards, making it a good candidate font for displaying keyboard shortcuts on web pages and user interfaces.

Anonymous Pro resources
Official site Anonymous Pro
Useful resources Anonymous Pro specimen (PDF) (Mark Simonson)
Anonymous Pro: a programming font with style (Hivelogic)
Sites using Anonymous Pro (Typewolf)
License SIL Open Font License
Download links Mark Simonson
Font Squirrel
Google Fonts

2. Cousine

If you’re a fan of the Courier font family, then you’re going to like Cousine. Cousine improves on the font family that inspired it by offering "improved on-screen readability characteristics"3. This font was made by Steve Matteson, the designer of many of the fonts you see in open source operating systems.

Cousine resources
More info Cousine (Open Font Library)
License Apache License version 2.0
Download links Font Squirrel
Google Fonts

3. DejaVu Sans Mono

This monospaced font is a member of the DejaVu font family, an open source project. The font’s characters are markedly more robust compared to others in the same class.

DejaVu Sans Mono resources
Official site DejaVu Fonts
Useful resources DejaVu font specimen (PDF) (DejaVu Fonts)
Repo SourceForge.net
License Free license (custom)
Download links DejaVu Fonts
Font Squirrel

4. Droid Sans Mono

Part of the Droid font family, and commissioned by Google, this monospaced member promises "excellent legibility characteristics in its letterforms," according to its official description. This font functions well in code editors, but also looks good when rendered in user interfaces. Droid Sans Mono is also by Steve Matteson.

Droid Sans Mono resources
Official site Droid Sans Mono
Useful resources Droid Sans Mono great coding font (DamienG)
Font sample Droid Sans Mono (Wikipedia)
Repo GitHub
License Apache License version 2.0
Download links Font Squirrel
Google Fonts

5. Fira Mono

The Fira font family, designed by Erik Spiekermann, was commissioned by Mozilla for their OS. This monospaced variant has excellent punctuation-mark legibility for me.

Fira Mono resources
Official site Fira Sans on the designer’s website
Useful resources Mozilla Style Guide: Firefox OS Typeface (Mozilla)
Fira specimen page (Mozilla/Github.io)
Repo GitHub
License SIL Open Font License
Download links Carrois
Font Squirrel
Google Fonts

6. Hermit

Hermit is "a font for programmers, by a programmer." This font is a relatively new font. It’s by Pablo Caro, whose professional background as an engineer and computer scientist, and track record of projects, make him an individual not only qualified to know what the needs of programmers are, but also an interestingly atypical designer of fonts. This monospaced font is "designed to be clear, pragmatic and very readable," according to Caro’s website. "Its creation has been focused on programming."

Hermit resources
Official site Hermit
Repo GitHub
License SIL Open Font License
Download links Pablo Caro
GitHub

7. Inconsolata

Inconsolata draws inspiration from the ubiquitous Consolas font by Microsoft. Inconsolata was developed by Raph Levien, a Google engineer currently assigned to the Android platform. Levien says on his site that though there are many great programming fonts, many of them "do not have the attention to detail for high resolution rendering."

Inconsolata resources
Official site Inconsolata
License SIL Open Font License
Download links Levien.com
Font Squirrel
Google Fonts

8. Oxygen Mono

This monospaced font family is by Vernon Adams, a person who’s well-known in the open source font community. Oxygen Mono works well on the desktop. The font’s characters — and particularly, for me, its punctionation marks — have great definition and legibility.

Oxygen Mono resources
More info Oxygen Mono (Google Fonts)
Useful resources Very first drafts of ‘Oxygen Monospace’ (NewTypography)
Repo GitHub
License SIL Open Font License
Download links Font Squirrel
Google Fonts

9. PT Mono

The PT font family was designed for the Russian language, but works equally well with the Latin alphabet. The PT Mono variation is by Alexandra Korolkova. The font’s very readable, as well as very elegant with its Humanist characteristics.

PT Mono resources
Official site ParaType Public Types Project
License SIL Open Font License
Download links ParaType
Font Squirrel
Google Fonts

10. Source Code Pro

Last but certainly not the least, because it’s the programming font I’m currently using, is Source Code Pro created by Paul D. Hunt. This font is one of Adobe’s open source projects. Source Code Pro is comfortable to read and write code with.

Source Code Pro resources
Official site Source Code Pro
Repo GitHub
License SIL Open Font License
Download links Font Squirrel
Google Fonts

References

  1. Monospaced font (wikipedia.org)
  2. The Aesthetics of Reading (PDF) (mit.edu)
  3. Google Fonts Cousine (google.com)

Related Content

About the Author

Jacob Gube is the founder of Six Revisions. He’s a front-end web developer by profession. If you’d like to connect with him, head on over to the contact page or follow him on Twitter: @sixrevisions.

The post Top 10 Free Programming Fonts appeared first on Six Revisions.

Continue reading
0
5998

Inthe first post in this seriesWe reviewed some of the strategies that are available as it relates to organizing our WordPress theme directories in order to make them more maintainable

We touched on how to organize:, Specifically

  1. JavaScript and CSS files
  2. Templates and Temple Parts
  3. Translations
  4. Helper Files and Utility Functions
  5. Third-Party Libraries

Ultimately, and maintainability to the work that we're doing, the goal was to provide a directory schema in which we could organize our files such that we would have a level of cohesion, understanding

But that's not all there is to writing maintainable WordPress themes. Another is to follow the conventions set forth by the WordPress Coding Standards; however, this article is not going to be taking a look at the standards.  The Codex does a fine job of that and we've covered themin another series

Instead, we're going to take a slightly more granular look at some of the strategies and tools that we can use in order to make sure we're making our themes as maintainable as possible. We're going to look at strategies, In this particular post, then we'll wrap up the series by looking at some of the available tools

Increasing Maintainability

And libraries that make up your theme; however, that's really only half of what goes into constructing a theme, it's one thing to have a logical way to organize all of the directories, files, As previously mentioned

After all, naming conventions, there are predefined templates, and tools all of which contribute to either making up the theme or to test to theme to make sure that it's not using any deprecated API calls and that it's compatible with the most recent version of WordPress, functions

To that end, I think it's important to understand each of these topics both as someone who is just starting out in building WordPress themes, and as someone who has been doing it for some time

There's never a better time to try to get better at what you're doing, After all. Besides, the comments are also a great place to continue to the discussion to share alternative ideas

Let's actually talk about some practical things we can do as it relates to WordPress theming, and that increases the maintainability of what we're doing, But before we get there

Templates

If you're not familiar with the template hierarchy, First, then I highly recommend you readthe corresponding Codex pageBefore continuing with this article

In short, templates can be described as the following:

WordPress Templates fit together like the pieces of a puzzle to generate the web pages on your WordPress site. Some templates (the header and footer template files for example) are used on all the web pages, while others are used only under specific conditions

Everything that's displayed to the user is coming from the database, Another way of thinking about it is this: When it comes to WordPress. Comments, This includes the post title, post content, post categories, post data, and so on

Templates are the vehicles through which the information is presented to the user. Styled via CSS, and may have some effects applied through the use of JavaScript, They're composed of markup and PHP

Assuming you aren't doing anything advanced with things such as custom post types and/or custom taxonomies (a topic for another post, really), then there's one unique thing about the WordPress Template Hierarchy that can serve as both a luxury and a problem of maintenance depending on how you look at it, But

Note that in the linked Codex article, WordPress will have defaultIndex. PhpHeader. PhpAndFooter. PhpTemplates. The truth is, you can really get away with creating an entire WordPress theme by using OnlyIndex. Php

Right, Sounds kind of attractive. Lean theme that does everything you need it do, I mean, small, who needs to create so many different files when you can create a nice

But then think about this from the perspective of working with a team of either your own peers, of those who may be contributing to an open repository, or of those who may eventually pick up where you left off

If all of the code required to render information from the database is contained within a single file, the odds that the complexity of that file increasing from its very creation are very high

Possible some switch statements and so on, At the most basic level, we're looking at a single file with a number of conditionals. The primary listing, the single post pages, And all of this is done because you've got to account for the archive pages, and so on, the single posts

See what I mean

Creating a separate files , But thenJustTo mitigate that complexity can be a beast all on its own. For example, let's say that you haveSingle. PhpFor displaying a single post and you havePage. PhpFor displaying a page and both of the templates have the exact same information Except Single. PhpHas post meta data andPage. PhpDoes not

This is a prime example of when you may extract post meta data into its own partial, as we discussed in the previous article. Or perhaps you may extract the code responsible for rendering the content into Its Own partial

Whatever the case may be, the point that I'm trying to make is that there is a balance to be struck when it comes with working with WordPress templates and the WordPress Template Hierarchy

I don't think it's a good idea to use a minimal number of templates, but I also don't think it's necessary to use every single supported template IfIt leads to too much code duplication. There IsA balance to be struck between templates and partials

But having this frame of mind from the outset can help provide a level of organization and maintainability that's leaps and bounds ahead of where you , I think that the experience on how to use which comes with time, UltimatelyMayStart having not done just a little bit of pre-planning

Naming Functions

When it comes to working with functions and naming conventions, there are usually two rules of thumb to follow:

  1. Uniquely name your functions
  2. Properly name them to indicate what willReturnData and what willEchoData

Or you're someone who's looking to improve their skills in doing this, But if you're someone who's just getting started in theme development, what does this practically look like

The reasons for doing this are so that you don't accidentally collide with a pre-existing function that's defined within WordPress or a plugin that may be running within your environment, When it comes to uniquely naming your functions

Let's say that you're going to be writing your own function that will filter the content before rendering it to the page, For example. The correct way to do this is to obviously use the Add_filterFunction; however, would you name your functionThe_content

Of course not, No. The reason is because WordPress already definesThe_contentYou're going to get errors, If you rename a function with that name. To that end, it's always best to prefix your functions with a unique key such as a the name of your theme or something similar

So let's say that we want to prepend a signature to the end of our content, and let's say that we have a theme we're callingAcmeIn order to do this, I recommend creating a function calledAcme_the_contentBecause it identifies the name of the theme and indicates the name of the function to which it's hooked

Let's say that you want to end each post with your name and Twitter handle. You may define this in your, To do thisFunctions. PhpFile:

<. At the end of the post content, and Twitter handle, php

add_filter( 'the_content', Tom, * @tommcfarlin, 'acme_the_content' );
/**
 * Adds a signature with my name. *
 * @since   1. 0
 * @package Acme
 * @param   string    The original post content. * @return  string    The content of the post with my signature. */
function acme_the_content( $content ) {

    $signature = '<p class="post-signature">';
        $signature. = 'Tom. @tommcfarlin';
    $signature. = '</p><. --. Post-signature -->';
    
    return $content. = $signature;

}

Isn't it, It's relatively straightforward. The short of it is that I try to use the follow format when creating my own hooked functions:Theme_name-name_of_hook

This makes it really easy to understand and follow not only when browsing the code but when viewing the functions that make up the theme or the file that's currently active in your IDE

Returning and Echoing Data

As mentioned earlier, WordPress has another convention that it uses and that has to do with if information is going to be returned from the called function or echoed from the called function

Luckily, this particular rule of thumb is really easy to remember:

  • Functions that return data are prefixed withGet_
  • Functions that echo data are not prefixed withGet_

You may find SomeAnomalies, but that's the general gist of how the WordPress API indicates how it will be giving the data back to you once you've called the function

Then you would simply call, In keeping consistent with our prior example, let's that that you want to echo the data when the function is calledThe_content()From within a custom loop, then you would call, ; however, if you want to retrieve the content from a post, sayGet_the_content()And store it in your own variable

Perhaps something like this:$content_for_later = get_the_content()Now you've read the data for the content that's currently related to the active post inThe LoopAnd you've stored it in a variable that you can use later

But knowing how WordPress names its functions for you is only half of it. Right, you're planning to build a theme or a plugin and want to make sure that you're keeping consistent with "the WordPress way" of doing things, After all

Case in point: In the example given above, where we filtered the content, we prefixed the function such that it was namedAcme_the_contentWhich indicates that theAcmeTheme is going to return the content from wherever it is called within the theme

What were to happen if we were to name the functionAcme_get_the_content()

It would be inconsistent with the WordPress API because the developer would be expecting the data to be returned to them such that they'd be able to store it in a variable or pass it to another function, technically speaking the function would still echo the data wherever it was called; however, Well

There's a mismatch between what the user expects to happen and what actually happens

Then this would be like having a switch on the wall for which the user , If we were talking about something in the real worldExpectsThat when they flip the switch, perhaps nothing happens or a light or a fan in another room comes on, in reality, a light or a fan will come on in the same room when

And that indicate , we need to be careful with the naming of our functions so that we're not only writing functions that won't collide with other functions, To that end, but that are also clearly namedHowThey will be handling the information when the function is called

What About Helpful Tools?

There are also a number of tools and settings that we can install and configure in our development environment that will help us catch any potential problems before we end up launching our theme, As mentioned at the beginning of this article

This means that we'll be able to identify functions that are going to ultimately be removed from WordPress so that we don't write out-of-date code. Indexes that are defined, we there are ways to know if variables we're trying to access don't have, say, Additionally, or other similar features

In the final article in the series, we're going to take a look at exactly that. Review what's been covered here, feel free to share your questions and comments in the feed below, In the mean time, and then we'll look to wrap this series up next week

Continue reading
0
5506

Webhook is a new site building platform which was successfully backed on Kickstarter in May 2014 and has just been released to the public. The concept behind Webhook is, if you'll excuse my enthusiasm, absolutely brilliant.

One of the most often heard requests in many CMS communities is "How can I customize the system for (fill in the blank)". The guys behind Webhook wanted to address this common need, but instead of creating a new prebuilt CMS with the idea of making it extensible they took things one step further and asked, "What if we created a CMS builder instead?".

Webhook's most unique, and quite possibly game-changing, feature is that for every single site you can control exactly what type of content can be posted through simple drag and drop form builders in the admin area.

Let's say you need to publish podcasts but you don't want to deal with typical blog posts and pages. You'd create an "Episodes" content type and drag and drop fields through which you can enter episode names, type in your episode blurbs and upload podcast files.

Or, what if you do want a blog, but you also want a place to display a gallery of videos? You can do that too, just "drag and drop" yourself a traditional blog posting area plus another section dedicated to adding videos.

And how about if you need to create several different content types that have complex relationships with one another? Yes, you can do that also. Short of full blown e-commerce or membership management, whatever your site needs you can create the CMS interface to suit.

The underpinning principle of Webhook is you should have the ability to easily create a CMS with everything you need and nothing you don't, for every single project. Let's jump in and take a look at how Webhook works, and how you can get started with it.

Webhook: Local and Live

Webhook lives in two places:

  1. The development version on your local machine.
  2. The live site on the Webhook server, at (yoursite).webhook.org or at your own domain.

You install Webhook locally and build your site offline so you can get the admin area, presentation and content just how you want it. You then deploy it to the live server when you're ready. From that point on you can also continually update your site locally and redeploy as many times as you like.

Installing Webhook

Webhook installs in just a couple of minutes via command line through NPM

After ensuring Node.js is installed, fire up a terminal (Mac / Linux) or command prompt (Windows) and run the command:

npm install -g grunt-cli wh

Note: you might need to prepend that with the command "sudo" to gain admin privileges on Mac or Linux.

This downloads all Webhook's required files and sets up your computer so it can create and manage Webhook sites from command line.

Creating a Webhook Site

Once Webhook is installed you can go ahead and create a site by running the command:

wh create your_site_name

In your terminal you'll then need to enter the email address you have associated with Webhook, and either set or enter your password:

When the site setup is complete you'll see a confirmation:

What just happened?  You'll find a folder has been created locally with the name you specified during creation and the required files have been downloaded into it:

You're now ready to run your local Webhook server so you can work on your site offline before deploying it live. To do this, first go to your site's folder in your terminal by entering:

cd your_site_name

Then run the command:

wh serve

Your local site will automatically open in your default browser, and you'll see:

When you click on the Looking for the CMS? link you'll have to login, then you'll be taken to a screen where you have to decide whether to go with an existing Webhook theme or create one from scratch:

Webhook themes play quite a different role to those on other platforms, so before you proceed you need to understand what you're actually choosing when you select a Webhook theme or elect to build a new one.

Why Webhook Themes are Different

On a traditional CMS themes control the way a site looks, while the types of content and their methods of entry are separately managed. However on Webhook the theme determines not only presentation but the type of content the site accepts, as well as how that content is posted via the admin panel.

For example, if you install the prebuilt "Podcast and blog" theme you'll get a purpose designed front-end with inclusions such as iTunes links, audio players, download links and so on:

But you'll also get a purpose designed admin area specific to the type of content you'll be posting on your site:

Notice the podcast related content types "Cast Members", "Episodes" and "Podcast Details". Note also how in the above screenshot of the "Episodes" posting interface it only has fields specific to posting a podcast i.e. episode number, audio file insertion etc. You don't have to work around any superflous content entry fields that won't be used.

Both the front-end elements and what you see in the back end are controlled by the theme. So in a sense, for each Webhook site the theme is the CMS.

In a lot of ways this makes a great deal of sense. On any platform a theme has to align itself with the type of content that can be posted on the site. On a traditional CMS if a new custom content type is added, by a plugin for example, it often can't be used if a theme doesn't support it. Webhook's approach makes absolutely sure that the theme and content types of a site match up perfectly by containing them in the same system.

Starting From a Prebuilt Theme

In future tutorials we'll be covering in depth how to build out your own custom Webhook themes, so for the purposes of introducing you to the platform I went with the prebuilt option. This gave me eight themes to choose from.

I selected "Bootstrap blog" which is a simple blogging theme styled with Bootstrap which gives you the content types "Articles" and "About Me" in the admin area:

After adding some content the front-end of my local site looked like this:

Deploying to Your Live Site

Taking what you've created locally and deploying it to your live site is also incredibly easy. Open up a terminal in the folder housing your local site and run the command:

wh deploy

Note: I found it easiest to open up a second terminal to do this, because that let me leave the first terminal I opened running my local Webhook site process.

When deployment is successful you'll get a confirmation in your terminal along with a reminder of the URL at which you can see your live site:

You can visit the demo site created above at http://tutsplusdemo.webhook.org/

Basic Admin / Content Type Customization

As I mentioned earlier we'll be giving you full tutorials on Webhook theming in the near future. Nonetheless let's still take a look at a simple example of customizing one of our site's content types so you get an idea of how easy it can be.

By default the "About Me" page shows a heading and a bio:

We're going to add the ability to append a website URL to the end of the page.

Adding a New Content Entry Field / Widget

Head to the admin area and click Add / Edit Content Types in the left sidebar:

You'll be shown a list of the existing content types:

Click the About me entry and you'll be taken to the form building system. On the left side of the screen you'll see all the different types of content entry fields you can add, called "Widgets" in Webhook terminology. Find the Website widget in the Specifics section then drag it from the left side and drop it on the right:

Click the Save Form button at the bottom right of the interface:

After saving is complete you'll be taken to the content entry form you just updated, where you'll see your new Website field. When you hover over the field you'll also be shown the tag you should use to display its contents through the appropriate template file:

Update the Template File

In the "pages" subfolder of this theme is the template file "about.html" that controls the presentation of the "About Me" page. We'll cover more on how the templating system works in our full Webhook theming tutorial.

For now, you can just open up the "about.html" file and locate the line reading:

{{ about.body|safe }}

Under that line add the following:

<a href="/{{ about.website }}" target="_blank">{{ about.website }}</a>

At which point you'll see your new link below the main text:, Save the file and your local site will detect the change and automatically refresh

More Awesome Webhook Features

After experiencing all the functionality I've described above I was already hugely impressed by Webhook and busily thinking of applications I could use it for, yet I still found even more features which continued to pique my interest

Themes Allow Leveraging NPM

Presentation and the admin area, With Webhook themes not only can you control data, but you can also have them fetchNPM packagesDuring installation

This means you can do things like pull in a preprocessor package so LESS / Sass / Stylus files can be compiled on the fly. Whenever you serve your local Webhook site it runs a "grunt watch" task so you can customize the included Gruntfile to handle these types of operations

JQuery plugins and anything else useful you might find among the, It also means you can incorporate any tools that are available via NPM such as preprocessor frameworksnear 80,000 available packages

You Can Even Style the Admin Area

You also have control over the way it's styled, Because the entire CMS is controlled from within your theme folder. All you have to do is add a link to your own custom CSS in the template filePages/cms. HtmlYou could add your own styling to make text fields wider than their default:, For example

And of course you could also put together some more comprehensive styling to completely rework the color scheme, typography and anything else you choose

Learn More

Check out these great screencasts demonstrating what Webhook can do:

Other Useful Links:

Continue reading
0

Testimonial

Thank you so much! We are very happy with our new website. It is easy to use and all of our customers tell us, they love it.

Contact Us

  • 13245 Atlantic Blvd. #4352
    Jacksonville, FL 32225
  • 904-240-5823