Skip to content

Instantly share code, notes, and snippets.

@mushu8
Created May 8, 2016 13:50
Show Gist options
  • Save mushu8/a3e2c227cae9897d14ae0d3f16d6e6fa to your computer and use it in GitHub Desktop.
Save mushu8/a3e2c227cae9897d14ae0d3f16d6e6fa to your computer and use it in GitHub Desktop.
extension UILabel{
func getRealWidth() -> CGFloat?{
guard let font = font else{
return nil
}
return (text! as NSString).sizeWithAttributes([NSFontAttributeName:font]).width
}
}
extension dispatch_queue_t{
static func generateQueue(label: String) -> dispatch_queue_t{
let str = generateUID()
let queue = dispatch_queue_create("com.\(label)\(str).queue", DISPATCH_QUEUE_CONCURRENT)
return queue
}
}
var Now: Double{
return NSDate().timeIntervalSince1970
}
extension CGFloat{
public static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
public static func random(min min: CGFloat, max: CGFloat) -> CGFloat {
return CGFloat.random() * (max - min) + min
}
func percent(ofValue of: CGFloat) -> CGFloat{
let cent = CGFloat(100)
let p = (self * cent) / of / cent
let q = p < 0 ? 0 : p
let r = q > 1 ? 1 : q
return r
}
}
extension Int{
public static func random(min min: Int, max: Int) -> Int {
return Int(arc4random_uniform(UInt32(max)) + UInt32(min))
}
}
extension UIButton{
func setFromLocalImage(name: String){
IMGEngine.getImage(name) { [weak self] (image) -> () in
self?.imageView?.image = image
}
}
}
extension UIImageView{
func setFromLocalImage(name: String){
IMGEngine.getImage(name) { [weak self] (image) -> () in
self?.image = image
}
}
}
extension String{
func toTag() -> String{
let allowed = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789")
let forbidden = allowed.invertedSet
let chars = componentsSeparatedByCharactersInSet(forbidden)
let mapped = chars.map { (s) -> String in
return s.capitalizedString
}
let joined = "#\(mapped.joinWithSeparator(""))"
return joined
}
func isValidEmailFormat() -> Bool{
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(self)
}
static func generateUID() -> String{
return genObjectId()
}
var noSpecialChar: String{
let charSet = NSCharacterSet(charactersInString: "1234567890").invertedSet
let phoneArray = componentsSeparatedByCharactersInSet(charSet)
let phoneNumber = phoneArray.joinWithSeparator("") as NSString
let slicedPhoneNumber = phoneNumber as String
return slicedPhoneNumber
}
var formattedString: String{
let charSet = NSCharacterSet(charactersInString: "1234567890").invertedSet
let phoneArray = componentsSeparatedByCharactersInSet(charSet)
let phoneNumber = phoneArray.joinWithSeparator("") as NSString
let slicedPhoneNumber = phoneNumber as String
let length = phoneNumber.length
var startIndexOffset = 0
if length >= 10{
startIndexOffset = length - 9
}
let range: Range<String.Index> = slicedPhoneNumber.startIndex.advancedBy(startIndexOffset)..<slicedPhoneNumber.endIndex
let substringed = slicedPhoneNumber.substringWithRange(range)
return substringed as String
}
}
extension UIView{
func roundCorner(r: CGFloat?){
guard let r = r else{
let c = frame.width / 2
layer.cornerRadius = c
return
}
defer{
layer.masksToBounds = true
}
layer.cornerRadius = r
}
func roundCorner(){
roundCorner(nil)
}
}
extension UIImage {
func compressImage() -> NSData {
// Drops from 2MB -> 64 KB!!!
var actualHeight : CGFloat = size.height
var actualWidth : CGFloat = size.width
let maxHeight : CGFloat = 1136.0
let maxWidth : CGFloat = 640.0
var imgRatio : CGFloat = actualWidth/actualHeight
let maxRatio : CGFloat = maxWidth/maxHeight
let compressionQuality : CGFloat = 0.8
if (actualHeight > maxHeight || actualWidth > maxWidth){
if(imgRatio < maxRatio){
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio){
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
let rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
drawInRect(rect)
let img = UIGraphicsGetImageFromCurrentImageContext();
let imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return imageData!;
}
}
extension UITextView: UITextViewDelegate {
// Placeholder text
@IBInspectable var placeholder: String? {
get {
// Get the placeholder text from the label
var placeholderText: String?
if let placeHolderLabel = self.viewWithTag(100) as? UILabel {
placeholderText = placeHolderLabel.text
}
return placeholderText
}
set {
// Store the placeholder text in the label
let placeHolderLabel = self.viewWithTag(100) as! UILabel?
if placeHolderLabel == nil {
// Add placeholder label to text view
self.addPlaceholderLabel(newValue!)
}
else {
placeHolderLabel?.text = newValue
placeHolderLabel?.sizeToFit()
}
}
}
// Hide the placeholder label if there is no text
// in the text viewotherwise, show the label
public func textViewDidChange(textView: UITextView) {
let placeHolderLabel = self.viewWithTag(100)
if !self.hasText() {
// Get the placeholder label
placeHolderLabel?.hidden = false
}
else {
placeHolderLabel?.hidden = true
}
}
// Add a placeholder label to the text view
func addPlaceholderLabel(placeholderText: String) {
// Create the label and set its properties
let placeholderLabel = UILabel()
placeholderLabel.text = placeholderText
placeholderLabel.sizeToFit()
placeholderLabel.frame.origin.x = 5.0
placeholderLabel.frame.origin.y = 5.0
placeholderLabel.font = self.font
placeholderLabel.textColor = UIColor.lightGrayColor()
placeholderLabel.tag = 100
// Hide the label if there is text in the text view
placeholderLabel.hidden = self.text.characters.count > 0
self.addSubview(placeholderLabel)
self.delegate = self;
}
}
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 {
guard layer.borderColor != nil else {
return nil
}
return UIColor(CGColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.CGColor
}
}
func setMenuGradient(){
setGradientBackground(topColor: "#5C584F", bottomColor: "#82898F")
}
func setGradientBackground(topColor top: String, bottomColor bottom: String){
let colors = [
UIColor(hexString: top),
UIColor(hexString: bottom)
]
let color = UIColor(gradientStyle:UIGradientStyle.TopToBottom, withFrame:bounds, andColors:colors)
backgroundColor = color
}
func fillWithView(view: UIView) -> ConstraintGroup{
return constrain(self, view){ Slf, Vi in
Vi.top == Slf.top
Vi.leading == Slf.leading
Vi.trailing == Slf.trailing
Vi.bottom == Slf.bottom
}
}
func setTransparency(percent: CGFloat){
AnimateWDuration(0.2, animations: {
self.alpha = percent
}, completion: nil)
}
}
extension Array{
func randomItem() -> Element{
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment