Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close
When we use extensions in swift it saves our lot of code by just few lines of code and also improves your code structure. Extensions are those you can write your function in default classes of iOS Useful extensions are :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
extension UIView { func applyBorder() -> Void { self.layer.borderColor = UIColor.black.cgColor // change yor color self.layer.borderWidth = 1.5 self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 1.0, height: 1.0) } } // or pass color while using this function extension UIView { func applyBorder(colours: UIColor) -> Void { self.layer.borderColor = colours.cgColor self.layer.borderWidth = 1.5 self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 1.0, height: 1.0) } } |
1 2 3 4 5 6 |
yourView.applyBorder() // or yourView.applyBorder(colours: UIColor.green) |
1 2 3 4 5 6 7 |
extension String { func removeString(completeString:String , remove: String) -> String { let aString = completeString let newString = aString.replacingOccurrences(of: "", with: remove, options: .literal, range: nil) return newString } } |
1 2 3 4 5 |
let name = string.removeString(completeString:"abcdef" , remove: "def") output is name = "abc" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import Kingfisher extension UIImageView { func setImage(imageUrl : String? ) { if URL(string: imageUrl) != nil && imageUrl.count > 0 { let resource = ImageResource(downloadURL: URL(string: imageUrl)!, cacheKey: imageUrl) self.contentMode = .scaleAspectFit self.kf.setImage(with: resource, placeholder: UIImage(named : "placeholder") , options: nil, progressBlock: nil, completionHandler: nil) } else{ self.image = UIImage(named : "placeholder") } } } |
1 2 3 |
yourImage.setImage(imageUrl: ImageUrl) //set your image to UIImageView |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
extension String { func widthOfString(usingFont font: UIFont) -> CGFloat { let fontAttributes = [NSFontAttributeName: font] let size = self.size(attributes: fontAttributes) return size.width } func heightOfString(usingFont font: UIFont) -> CGFloat { let fontAttributes = [NSFontAttributeName: font] let size = self.size(attributes: fontAttributes) return size.height } } |
1 |
let stringSize = buttonText.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) |
1 2 3 4 5 6 7 8 9 10 11 |
extension Bundle { static func loadView<T>(fromNib name: String, withType type: T.Type) -> T { if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T { return view } fatalError("Could not load view with type " + String(describing: type)) } } |
1 2 3 |
var emptyView : EmptyView? // your xib emptyView = Bundle.loadView(fromNib: "EmptyView", withType: EmptyView.self) // it will load your xib |
Be the first to comment.