Useful Swift Extensions
Herkese merhaba. Ben Mert. Sizlere çalıştığım projelerde sürekli olarak kullandığım bazı extensionlardan bahsetmek istiyorum.
- UIColor Extension — Hexadecimal Renk Kodları
extension UIColor {
convenience init(hex: String, alpha: CGFloat = 1.0) {
let hexString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
let scanner = Scanner(string: hexString)
if hexString.hasPrefix("#") {
scanner.currentIndex = hexString.index(after: hexString.startIndex)
}
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
Kullanım
let customColor = UIColor(hex: "#FF5733")
let colorWithAlpha = UIColor(hex: "#FF5733", alpha: 0.5)
Verilen hex kodunu UIColor’a dönüştürür ve isteğe bağlı bir alfa değeri verebilirsiniz.
2. String Extension — Date’e Çevirme
extension String {
func toDate(format: String = "yyyy-MM-dd") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
}
Kullanım
let customDate = "2023-03-15".toDate()
String değerde verilen bir tarihi Date formatına çevirir. (Date formatını kullanım biçiminize göre şekillendirebilirsiniz.)
3. Array Extension — Rastgele Eleman Seçme
extension Array {
var randomElement: Element? {
return isEmpty ? nil : self[Int(arc4random_uniform(UInt32(count)))]
}
}
Kullanım
let fruits = ["apple", "banana", "grape", "orange"]
print(fruits.randomElement ?? "No elements")
Array içerisinden rastgele eleman seçer.
4. UIViewController Extension — Klavye Gizleme
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
}
@objc func hideKeyboard() {
view.endEditing(true)
}
}
Kullanım
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
}
}
UITextField, UISearchBar vs. kullanırken en çok kullandığım extension. Burada, view’da klavye harici bir yere dokunulduğunda klavyenin gizlenmesini sağlar.
5. UILabel Extension — Label’a Icon Ekleme
extension UILabel {
func addIcon(icon: UIImage, text: String, iconSize: CGSize, xOffset: CGFloat, yOffset: CGFloat) {
let attachment = NSTextAttachment()
attachment.image = icon
attachment.bounds = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: iconSize)
let attachmentString = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString(string: "")
mutableAttributedString.append(attachmentString)
let textString = NSMutableAttributedString(string: " \(text)")
mutableAttributedString.append(textString)
self.attributedText = mutableAttributedString
}
}
Kullanım
let exampleLabel = UILabel()
exampleLabel.addIcon(icon: UIImage(named: "imgExample"), text: "Summary", iconSize: CGSize(width: 17, height: 17), xOffset: -2, yOffset: 0)
Label’ın yanına icon koymamıza yarar.
6. UIControl Extension — UIButton’a action ekleme
extension UIControl {
func addAction(for controlEvents: UIControl.Event = .touchUpInside, _ closure: @escaping()->()) {
addAction(UIAction { (action: UIAction) in closure() }, for: controlEvents)
}
}
Kullanım
let exampleButton = UIButton()
exampleButton.addAction {
print("Hello World!")
}
Bu extension bizi butona target vermekten ve ekstra fonksiyon yazmaktan kurtarır. Okunulabilirliği arttırır, daha düzenli bir görüntü oluşur.
Sizler için hazırladığım bu yazıyı umarım beğenmişsinizdir. Buna benzer yazılarımın devamı gelecek. Tüm sorularınız için bana Twitter ve mrtctns22@gmail.com üzerinden ulaşabilirsiniz. İyi çalışmalar dilerim.