Extension method nedir? Adından da anlaşılacağı üzere genişletme methodu. Yani var olan yapılarımıza kendi methodlarımızı ekleme işlemleridir.
Örnekler:
Mesela bir integer sayının karesini alan bir extension method yazmak istiyorsunuz.
extension Int
{
func Karesi() -> Int {
return self* self
}
}
print(5.Karesi()) //25
Mesela bir string'in başında ve sonundaki fazladan gelen boşlukları silmek istiyorsunuz. Swift gibi saçma şekilde uzatmaktansa extension method haline getirip aşağıdaki şekilde kullanabilirsiniz.
extension String
{
func trim() -> String
{
return self.trimmingCharacters(in: NSCharacterSet.whitespaces)
}
}
print(" Kodstrap.Com ".trim()) //"Kodstrap.Com"
UIImageView'e internetten bir url'den resim basmak istiyorsunuz.
extension UIImageView {
func Load(url:String) {
let newUrl = URL(string: url)
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: newUrl!) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
}
imgMain.Load(url: "http://www.biradres.com/resim.jpg")
UIColor sınıfına hex ve rgb ile renk çağırmak istiyorsak
extension UIColor
{
convenience init(hex: String) {
let heX = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: heX).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.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)
}
static func RGB(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor {
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
}
UIColor(hex: "#ffffff")
UIColor.RGB(r: 100, g: 50, b: 150, a: 1 )
Bir View'nize border eklemek istiyorsunuz.
extension UIView {
func addBorder(_ size:CGFloat, red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat, way:String)
{
let uiColour = UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha);
let border = CALayer();
border.backgroundColor = uiColour.cgColor;
if way == "top"
{
border.frame = CGRect(x: 0, y: 0, width: frame.width, height: size)
}
else if way == "bottom"
{
border.frame = CGRect(x: 0, y: frame.height - size, width: frame.width, height: size)
}
else if way == "left"
{
border.frame = CGRect(x: 0, y: 0, width: size, height: frame.height)
}
else
{
border.frame = CGRect(x: frame.width - size, y: 0, width: size, height: frame.height)
}
layer.addSublayer(border);
}
}
myView.addBorder(1, red: 184, green: 218, blue: 97, alpha: 1, way: "bottom");
#swift #extensionmethods #xcode #swiftdersleri #iosdersleri
İyi Kodlar!