Skip to content

Instantly share code, notes, and snippets.

@vparihar01
Last active November 11, 2016 15:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vparihar01/92888ce9fbc0efaad121 to your computer and use it in GitHub Desktop.
Save vparihar01/92888ce9fbc0efaad121 to your computer and use it in GitHub Desktop.
Swift 2 + IOS >8.4 tips, tricks and code snippets for various UI's and functionality.

Swift 2 + IOS 8.4 & above Code Samples, tips, tricks for various UI customization

  • UIViewExtension - UIView extension for adding view border , corner radius , border color, border width and setting custom border like left,right,top and bottom borders from Storyboard.
  • UILabelCustomize - Add the shadow to UILabel. Customize the uilabel, to add the border with color, make it round and translate the inner text to right by X.
  • UIColorHexToColor - Convert the hex color into ios colors.
  • UIbuttonExtension - Text padding/inset from left to UIButton.
  • buttonBorder - IOS Add top , bottom, left and right button to button/text field.
  • buttonPadding - Add little text padding/inset from left
  • StringExtension - Truncate String in Swift
func showborder(){
let bottomBorder = CALayer()
let width = CGFloat(0.5)
bottomBorder.borderColor = UIColor(hexString: "EEEEEE").CGColor
bottomBorder.frame = CGRect(x: 0, y: self.contentView.frame.size.height - width, width: UIScreen.mainScreen().bounds.size.width, height: 0.5)
bottomBorder.borderWidth = width
self.contentView.layer.addSublayer(bottomBorder)
}
func hideborder(){
let bottomBorder = CALayer()
let width = CGFloat(0.5)
bottomBorder.borderColor = UIColor.clearColor().CGColor
bottomBorder.frame = CGRect(x: 0, y: self.contentView.frame.size.height - width, width: UIScreen.mainScreen().bounds.size.width, height: 0.5)
bottomBorder.borderWidth = width
self.contentView.layer.addSublayer(bottomBorder)
}
let topBorder = CALayer()
let bottomBorder = CALayer()
let leftBorder = CALayer()
let rightBorder = CALayer()
let width = CGFloat(0.5)
topBorder.borderColor = UIColor(red: 94/255, green: 94/255, blue: 94/255, alpha: 1).CGColor
topBorder.frame = CGRect(x: -15, y: 0.5, width: self.button.frame.size.width - width, height: width)
topBorder.borderWidth = width
bottomBorder.borderColor = UIColor(red: 94/255, green: 94/255, blue: 94/255, alpha: 1).CGColor
bottomBorder.frame = CGRect(x: -15, y: self.button.frame.size.height - 1, width: self.button.frame.size.width - 1, height: 1)
bottomBorder.borderWidth = width
leftBorder.borderColor = UIColor(red: 94/255, green: 94/255, blue: 94/255, alpha: 1).CGColor
leftBorder.frame = CGRect(x: -14.5, y: 0.5, width: width, height: self.button.frame.size.height)
leftBorder.borderWidth = width
rightBorder.borderColor = UIColor(red: 94/255, green: 94/255, blue: 94/255, alpha: 1).CGColor
rightBorder.frame = CGRect(x: self.button.frame.size.width - 16, y: 0.5 , width: width, height: self.button.frame.size.height)
rightBorder.borderWidth = width
button.layer.addSublayer(topBorder)
button.layer.addSublayer(bottomBorder)
button.layer.addSublayer(leftBorder)
button.layer.addSublayer(rightBorder)
// Add little text padding/inset from left
button.layer.sublayerTransform = CATransform3DMakeTranslation(15, 0, 0)
// A Simple exntention for string to truncate the string in Swift 2.0 and above.
extension String {
/// Truncates the string to length number of characters and
/// appends optional trailing string if longer
func truncate(length: Int, trailing: String? = nil) -> String {
if self.characters.count > length {
return self.substringToIndex(self.startIndex.advancedBy(length)) + (trailing ?? "")
} else {
return self
}
}
}
extension UIButton {
public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let buttonSize = self.frame.size
let widthToAdd = (44-buttonSize.width > 0) ? 44-buttonSize.width : 0
let heightToAdd = (44-buttonSize.height > 0) ? 44-buttonSize.height : 0
let largerFrame = CGRect(x: 0-(widthToAdd/2), y: 0-(heightToAdd/2), width: buttonSize.width+widthToAdd, height: buttonSize.height+heightToAdd)
return (CGRectContainsPoint(largerFrame, point)) ? self : nil
}
func customizeTheButton(borderWidth: CGFloat, borderColor: UIColor, borderRadius: CGFloat, shiftTextByX: CGFloat) {
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.CGColor
self.layer.masksToBounds = true
self.layer.cornerRadius = borderRadius
}
}
//USAGE in code
self.button.customizeTheButton(0.9, borderColor: UIColor(red: 1, green: 1, blue: 1, alpha: 0.25), borderRadius: 20, shiftTextByX: 15)
// TO convert the hex color into ios colors
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
NSScanner(string: hex).scanHexInt(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
// USAGE
UIColor(hexString: "979797")
Here's a correct table of percentages to hex values. E.g. for 50% white you'd use #80FFFFFF.
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
extension UILabel {
// Add the shadow to UILabel
func addOuterShadow(shadowColor: CGColor = UIColor.blackColor().CGColor,
shadowOffset: CGSize = CGSizeMake(0.0, 0.5),
shadowRadius: CGFloat = 1,
shadowOpacity: Float = 1) {
layer.shadowColor = shadowColor
layer.shadowOffset = shadowOffset
layer.shadowRadius = shadowRadius
layer.shadowOpacity = shadowOpacity
layer.masksToBounds = false
layer.shouldRasterize = true
}
// Customize the uilabel, to add the border with color, make it round and translate the inner text to right by X.
func customizeTheLabel(borderWidth: CGFloat, borderColor: UIColor, borderRadius: CGFloat, shiftTextByX: CGFloat) {
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.CGColor
self.layer.masksToBounds = true
self.layer.cornerRadius = borderRadius
self.layer.sublayerTransform = CATransform3DMakeTranslation(shiftTextByX, 0, 0)
}
}
//
// UiViewExtension.swift
// Yogurt
//
// Created by Vivek Parihar on 13/11/2015.
// Copyright © 2015 Yogurt Lbas. All rights reserved.
//
import UIKit
// MARK: - UIView
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
return UIColor(CGColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.CGColor
}
}
@IBInspectable var leftBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = UIColor(CGColor: layer.borderColor!)
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var topBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
}
}
@IBInspectable var rightBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: bounds.width, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var bottomBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: bounds.height, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
}
}
}
class AppDelegate: UIResponder, UIApplicationDelegate, UIAlertViewDelegate {
var window: UIWindow?
var moviePlayer: MPMoviePlayerViewController!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var movieUrl: NSURL!
// Adding the movie animation while application starts.
movieUrl = NSBundle.mainBundle().URLForResource("Launch_animation_mov", withExtension: "mov")!
moviePlayer = MPMoviePlayerViewController(contentURL: movieUrl)
moviePlayer.moviePlayer.scalingMode = MPMovieScalingMode.Fill
moviePlayer.moviePlayer.view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height)
let backGroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height))
backGroundView.backgroundColor = UIColor.whiteColor()
moviePlayer.moviePlayer.backgroundView.addSubview(backGroundView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "moviePlayerEnd:", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
moviePlayer.moviePlayer.setFullscreen(true, animated: false)
moviePlayer.moviePlayer.controlStyle = MPMovieControlStyle.None
moviePlayer.moviePlayer.repeatMode = MPMovieRepeatMode.None
moviePlayer.moviePlayer.play()
window!.rootViewController = moviePlayer
self.window?.makeKeyAndVisible()
return true
}
func moviePlayerEnd(notification: NSNotification) {
DLog("Movie player did end playing")
NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
// TO prevent the black screen when movie ends.
if self.moviePlayer == self.moviePlayer {
self.moviePlayer.moviePlayer.pause()
}
// View controller you want to show when launch video ends.
let destinationVC = TabBarController()
// Make sure it will match the appearing view background color.
destinationVC.view.backgroundColor = UIColor.whiteColor()
// Trantion of rootViewcontroller from appdelegate to make it smoother using UIView.transitionWithView.
UIView.transitionWithView(self.window!, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve , animations: { () -> Void in
self.window?.rootViewController = destinationVC
}, completion: nil)
self.window?.makeKeyAndVisible()
if self.moviePlayer != nil{
/* We got the thumbnail image. You can now use it here */
if self.moviePlayer == self.moviePlayer {
self.moviePlayer.moviePlayer.stop()
self.moviePlayer.moviePlayer.view.removeFromSuperview()
self.moviePlayer = nil
}
}
}
}
// Trantion of rootViewcontroller from appdelegate to make it smoother using UIView.transitionWithView.
let destinationVC = TabBarController()
destinationVC.view.backgroundColor = UIColor.whiteColor()
UIView.transitionWithView(self.window!, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve , animations: { () -> Void in
self.window?.rootViewController = destinationVC
}, completion: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment