Alternative solution of NSDictionaryOfVariableBindings in Swift, swiftnsdictionary

Source: Internet
Author: User

Alternative solution of NSDictionaryOfVariableBindings in Swift, swiftnsdictionary

I haven't written anything in a few days. I have to spend some time practicing my pen and work hard ~

I recently switched from OC to Swift2. Since Swift has never been very serious, its understanding of this language is basically a ball... I have to feel that Apple is moving fast, and Swift has not yet learned yet, so it will be 2... So I realized that it could be 2 if I didn't learn it again ~~ It took some time to read The full-book "The Swift Programming Language" and finally he could write something ~ Followed by the problem.


I used to hand-writing automatic layout, or the old saying: Where can I use SB (StoryBoard ~~ This is also because of some problems ~ How can I create a VFL dictionary for multiple views? Because Swift does not support macro definition, the kind of 'nsictionaryofvariablebindings 'is useless. After searching the Internet, there is no serious solution ~~ Hand-written dictionary... I can't write the encoding of this type of soil hammer, and I decided to switch to StoryBoard to make the interface.


The final result is... My StoryBoard is too unskilled, or the Xcode7 StoryBoard has bugs, each time you enable Xcode, the control with the constraint added will change the size of the control, causing a warning that the display effect of the design interface is different from that of the running interface, at the same time, with the increase of SB content, the computer will become card (although the contribution of the lossless player is greater ...), Looking for specific content is even more of a disaster... As for the design of ScrollView in IB, it is even more boring... After all, the abbreviation is SB... In general, there is no positive impact on efficiency... At least for me ~


Well, handwriting Automatic Layout is true love...


So the problem is back to the origin ~ In Swift, how should we deal with the hand-writing Automatic Layout of the trouble place...


I thought, since macro processing is not allowed, you can't stop me in this way ~ The idea is to pass the view array, and then determine the variable names of these views in the object during running. Just create an array and simulate the macro function ~ So I wrote an Extension for NSObject. Why is it NSObject? The reason is very simple. Most of the hand-writing automatic la s are written for UIViewController, but there will still be situations where the automatic la s are written in UIView ~ So NSObject is more reasonable.


The idea is ready, and the content is relatively simple ~


<span style="font-size:14px;">    func dictForViews(views:[UIView]) -> [String : UIView] {        var count:UInt32 = 0        var dicts:[String : UIView] = [:]                let ivars = class_copyIvarList(self.classForCoder, &count)        for var i = 0; i < Int(count); ++i{            let obj = object_getIvar(self, ivars[i])            if let temp = obj as? UIView{                views.contains(temp)                let name = String.fromCString(ivar_getName(ivars[i]))!                dicts[name] = temp                if dicts.count == views.count{ break }            }        }                free(ivars)                return dicts    }</span>



In this way, the dictionary code can be simply written.


<span style="font-size:14px;">let views = dictForViews([view1,view2])</span>



Print it out:


[View2: <UIView: 0x7f8820fcb610; frame = (0 0; 0 0); layer = <CALayer: 0x7f8820fc1960>,

View1: <UIView: 0x7f8820fe17b0; frame = (0 0; 0 0); layer = <CALayer: 0x7f8820fbe560>]


OK. Basic requirements are met.


By the way, because I wrote this method and wrote something to use together, it's also a little bit of a joke ~ To put it simply, a normal VFL statement is written like this.


|-[View1 (= view2)] [view2]-|


I personally do not like to write pure strings, because sometimes variable names are defined very long for program readability ~ In order to write VFL, it is really painful to write this name over and over again. Even if you copy and paste the name, it is also a headache. So I wrote a method to get the attribute name through the object ~ It is good to use with the Swift string insertion mechanism. Although VFL itself may be long side, it may even slightly affect readability, but if you are familiar with it, there is still no problem ~


The method is simple:


<span style="font-size:14px;">     func nameFor(view:UIView) -> String{        var count:UInt32 = 0        let ivars = class_copyIvarList(self.classForCoder, &count)        for var i = 0; i < Int(count); ++i{            let obj = object_getIvar(self, ivars[i])            if let temp = obj as? UIView{                if temp === view {                    return String.fromCString(ivar_getName(ivars[i]))!                }            }        }                free(ivars)                return ""    }</span>


Here, 'string' is returned instead of 'string? '

For the normal Swift method, 'string? 'Obviously it is a more reasonable method, but the problem is that this method is equivalent to an inline method. It is good to directly use the return value. If 'string' is used? 'You need to add one at a time '! ', This is too painful... So I had a shameless compromise ~ After this method is used, VFL becomes


|-[\ (NameFor (view1) (==\ (nameFor (view2)] [\ (nameFor (view2)]-|


I think there should be at least two points if there is any benefit in writing this article. First, we should avoid the input errors caused by pure handwritten strings, second, it saves the trouble of replacing the string by refactoring and changing the variable name ~ Since both methods and variables are intelligently prompted During writing, it does not seem so troublesome to write ~ It's nice except getting longer ~ How to write it.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.