Category

Swift

Adding Icons To UITextField

I promise to keep this on short .

I’m really having a good time as I continue learning sweet. Progress on my attempt to create an ‘Instagram clone’ is pretty good. Source code is available on Github.

All was going well until I tried adding icons to UITextField but it only lead to frustrations. So I thought I’d share how I got past this. By the end of this blog you should be able to add images you your TextFields

Icon_TextField

So let’s get started.

I’m assuming you have created your outlets from the storyboard to the related ViewController.

1. Define the ImageView:
let imageView = UIImageView();
let imageEmail = UIImage(named: "ic_email.png");
imageView.image = imageEmail;

2. Set up the frame for the image view:

imageViewEmail.frame = CGRect(x: 5, y: 5, width: 20, height: 20)

No_Padding_TextField

4. Setting padding: 

If you look at the above image, the icons seem to appear above the text. To fix this, you need padding to the textfield.

let paddingView = UIView(frame: CGRectMake(0, 0, 25, self.emailTextField.frame.height))
emailTextField.leftView = paddingView

This will add some space to the left of the text.

Icon_TextField

Complete Code

Happy coding.

The UIControllerView

UICollectionView was added last year with iOS 6. I decided to spend some time over the weekend and see what I can come up with. It was not easy, well it was until I build my project and there spacing of the cell items was different on various screen sizes.Wrong Cell spacing

What in the world is going on here?? I check the storyboard and the constraints are correctly configured. So I decide to go through the documentation and baaaayaaam!!

func collectionView(collectionView: UICollectionView, layout collectionViewLayout:

UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{

}

jesus_ok___telegram_sticker_by_jinkazama84-d8qqmqi

 We are not yet out of the woods. We just need to add a few lines of code and we are good to go.

1. Define the cell spacing
let cellSpacing = CGFloat(1)

2. Set left/right margin
let leftRightMargin = CGFloat(0)

3. Define the number of columns
let numColumns = CGFloat(3)

4. Get the width of the screen.
let screenWidth = UIScreen.mainScreen().bounds.width

5. Calculate the width
let totalCellSpace = cellSpacing * (numColumns - 1)
let width = (screenWidth - leftRightMargin - totalCellSpace) / numColumns

6. Set the height of the cell
let height = CGFloat(120)

Complete Code


 

Final Result

Correct cell Spacing

Misson complete. Things look better now. The cells size is now dynamic on all screens. Victory.

telegram-i-migliori-stickers-da-aggiungere-alla-vostra-collezione-3

Happy coding. My #Swift adventure continues.