-rw-r--r-- 712B Aug 18, 2016 · 14091F5 · ~1 min

A Block (Closure) as a Class Property in Swift

swift шпаргалки

An example of using a block (closure) as a class property in Swift.

class ChatViewController: UIViewController {

    private var someClosure: (() -> Void)?
    private var anotherClosure: ((arg: Double) -> Bool)?

    func executeClosures() {
        if self.someClosure != nil {
            self.someClosure()
        }

        if self.anotherClosure != nil {
            let boolResult = self.anotherClosure(arg: 2.0)
        }
    }

    func addSelfClosure(closure: (() -> Void)!) {
        self.someClosure = closure
    }

    func printSomething() {
        self.addSelfClosure() {
            print("closure called")
        }
        self.executeClosures() // prints: closure called
    }

} 
[↵] open page blok-zamykanie--kak-svojstvo-klassa-v-swift.md
-rw-r--r-- 651B Aug 18, 2016 · AC73616 · ~1 min

CompareShots v1.2

compareshots ios приложения

CompareShots version 1.2 has been released.

I released it because one of the users emailed me asking to hide the logo and text after an image is selected, because otherwise, if the image is not full-screen, they stick out from behind it or show through. While I was at it, I decided to level up the app a bit more. At last, my subscription to various new libraries came in handy. Now you can draw on top of images. With different colors and brushes of different sizes. One evening, and this beauty was ready :)

Download

[↵] open page compareshots-v1-2.md
-rw-r--r-- 5.5K Aug 17, 2016 · 512B298 · ~4 min

Thoughts on Assassin's Creed Unity

assassin's creed игры

Assassin's Creed Unity

[↵] open page vpechatleniya-ot-assassin-s-creed-unity.md
-rw-r--r-- 2.9K Aug 12, 2016 · EC7C9DE · ~2 min

Custom Badge for UITabBarController in Swift

swift шпаргалки uitabbarcontroller

It was 2016, and to change the colors of a badge inside a tab you still had to create your own UI element and add it to the tab bar manually. A working solution in Swift:

// MARK: - UITabBarController extension for badges
extension UITabBarController {

    /**
    Set badges

    - parameter badgeValues: values array
    */
    func setBadges(badgeValues: [Int]) {

        for view in self.tabBar.subviews {
            if view is CustomTabBadge {
                view.removeFromSuperview()
            }
        }

        for index in 0...badgeValues.count-1 {
            if badgeValues[index] != 0 {
                addBadge(
                    index: index,
                    value: badgeValues[index],
                    color:UIColor.yellowColor(),
                    font: UIFont.systemFontOfSize(11)
                )
            }
        }

    }

    /**
    Add badge for tab

    - parameter index: index of tab
    - parameter value: badge value
    - parameter color: badge color
    - parameter font: badge font
    */
    func addBadge(index: Int, value: Int, color: UIColor, font: UIFont) {
        let badgeView = CustomTabBadge()

        badgeView.clipsToBounds = true
        badgeView.textColor = UIColor.whiteColor()
        badgeView.textAlignment = .Center
        badgeView.font = font
        badgeView.text = String(value)
        badgeView.backgroundColor = color
        badgeView.tag = index
        tabBar.addSubview(badgeView)

        self.positionBadges()
    }

    override public func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.tabBar.setNeedsLayout()
        self.tabBar.layoutIfNeeded()
        self.positionBadges()
    }

    /**
    Positioning
    */
    func positionBadges() {

        var tabbarButtons = self.tabBar.subviews.filter { (view: UIView) -> Bool in
            return view.userInteractionEnabled // only UITabBarButton are userInteractionEnabled
        }

        tabbarButtons = tabbarButtons.sort({ $0.frame.origin.x < $1.frame.origin.x })

        for view in self.tabBar.subviews {
            if view is CustomTabBadge {
                let badgeView = view as! CustomTabBadge
                self.positionBadge(badgeView, items:tabbarButtons, index: badgeView.tag)
            }
        }
    }

    /**
    Position for badge

    - parameter badgeView: badge view
    - parameter items: tab bar buttons array
    - parameter index: index of tab
    */
    func positionBadge(badgeView: UIView, items: [UIView], index: Int) {

        let itemView = items[index]
        let center = itemView.center

        let xOffset: CGFloat = 12
        let yOffset: CGFloat = -14
        badgeView.frame.size = CGSizeMake(17, 17)
        badgeView.center = CGPointMake(center.x + xOffset, center.y + yOffset)
        badgeView.layer.cornerRadius = badgeView.bounds.width/2
        tabBar.bringSubviewToFront(badgeView)
    }

}

/// Custom UILabel class for badge view
class CustomTabBadge: UILabel {}
[↵] open page kastomnyj-bejdzh-dlya-uitabbarcontroller-na-swift.md
-rw-r--r-- 1.0K Aug 9, 2016 · FDC24F3 · ~1 min

Delay Function in Swift

swift шпаргалки

A very nice bit of syntactic sugar: a function for running code with a delay via Grand Central Dispatch using dispatch_after:

Update 2024. Swift 5.5+

If you need a delay inside an async function:
func someMethod() async throws {
    // sleep for 2 seconds
    try await Task.sleep(nanoseconds: NSEC_PER_SEC * 2)
}

Swift 2:

/**
Delay function using GCD. Syntax sugar.

- parameter delay: delay in seconds
- parameter closure: closure code to execute after delay
*/
func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
    dispatch_get_main_queue(), closure)
}

Swift 3:

/**
Delay function using GCD. Syntax sugar.

- parameter delay: delay in seconds
- parameter closure: closure code to execute after delay
*/
func delay(_ delay: Double, closure:()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

Usage:

delay(0.4) {
    // code
}
[↵] open page funktsiya-zaderzhki-na-swift.md
-rw-r--r-- 705B Jun 14, 2016 · B548F4B · ~1 min

A modal UIViewController with transparency

swift шпаргалки

Cheat sheet: how to present a UIViewController over another one so that it is semi-transparent and the content underneath shows through.

In Storyboard, set the Segue Kind field to «Present Modally». For the UIViewController you are showing, set the background color to Clear Color, then create an inner background (an image or another UIView) with an alpha value, for example 0.5.

In code:

self.performSegueWithIdentifier("segueName", sender: self)

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "segueName" {
        let vc = segue.destinationViewController as! YourViewController
        vc.modalPresentationStyle = .Custom
    }
}
[↵] open page modal-nyj-uiviewcontroller-s-prozrachnost-yu.md
-rw-r--r-- 1.1K May 26, 2016 · EB1C751 · ~2 min

Blog redesign

бложек

I decided to study what websites look like in Google's Material Design. I found their Material Design Lite library and dropped it into the site. It seems more readable now, it has responsive design out of the box so it can be read on phones, and it looks better on Retina now too. It is convenient when you can assemble what you like from ready-made pieces. I like the result more than what you can build, for example, with Twitter Bootstrap.

I thought about the header for a long time and in the end lovingly stole the idea from Apple's page dedicated to WWDC '16 :) I implemented it in SVG and animated the cursor in JS (though only in the desktop version). I looked at Polymer, but it did not really start up for me right away, and I had already done a lot with MDL by then. The idea of web components is certainly cool, and it looks great semantically, but for now I will postpone it until browser support gets better. There is also a feeling that everything there is heavily tied to Node.JS, and I no longer want to rewrite it in Node — I am waiting for new Swift releases so I can rewrite it in Swift.

[↵] open page redizajn-bloga.md
makoni@arm1:~/blog$ cd ../page-10/ // ← previous cd ./page-12/ // more posts →