Parth Adroja
Parth Adroja

Reputation: 13514

Regular Expression to replace CGRectMake

As CGRectMake is not available in swift 3.0 and migrator did not convert it i need to manually replace it and it is used more than 300 times in my code so can anyone help me in this to develop regular expression so i can find and replace code. What i want to do is to convert

CGRectMake(a,a,a,a) here a is some value.

to

CGRect(x: a, y: a, w: a, h: a)

Upvotes: 3

Views: 320

Answers (4)

Harshal Bhavsar
Harshal Bhavsar

Reputation: 1673

I have one different way to solve this problem.

Step 1

In the following line

CGRectMake(a,a,a,a) 

Just replace CGRectMake with CGRectMakeCustom so all will look like

CGRectMakeCustom(a,a,a,a)

Step 2

Create new Global function in the project as follows

func CGRectMakeCustom(x: Double, y: Double, width: Double, height: Double) -> CGRect
    {
        return CGRect(x: x, y: y, width: width, height: height)
    }

In this way it will be easy for you to start woking on Swift3

Upvotes: 0

Suyog Patil
Suyog Patil

Reputation: 1616

EDIT - With Regex:

CGRectMake\(([^,]*),([^,]*),([^,]*),([a-z|0-9|.|A-Z]*)\)

and replace with

CGRect\(x:\1, y:\2, width:\3, height:\4\)

Using regex we can not get the value of x,y,width,height dynamically.

So Alternative solution to above is,

  • Replace all the CGRectMake( with appdelegateobject.CGRectMakeWrapper("
  • At the end add " only.

Means in your case you will replace CGRectMake(a,a,a,a) to appdelegateobject.CGRectMakeWrapper("a,a,a,a"

where appdelegateobject is the appdelegate shared instance object where you will define CGRectMakeWrapper function having string parameter as shown below :

func CGRectMakeWrapper(str: String) -> CGRect {

    var rect = CGRectZero

    if(str.characters.count > 0)
    {
        var arr = str.componentsSeparatedByString(",")

        if(arr.count == 4)
        {
            rect = CGRect(x: CGFloat((arr[0] as NSString).doubleValue), y: CGFloat((arr[1] as NSString).doubleValue), width: CGFloat((arr[2] as NSString).doubleValue), height: CGFloat((arr[3] as NSString).doubleValue))
        }

    }



    return rect
}

var rect = "10.0,10.0,100,100" //String


var rect1 = CGRectMakeWrapper(rect)  //CGRect

I have shown sample string as rect and passed to CGRectMakeWrapper function which will return a rect. You can define this CGRectMakeWrapper function in common class which is accessible to all classes(e.g Appdelegate file).

Upvotes: 1

kinjal patel
kinjal patel

Reputation: 396

You can change mode to regular expression while searching and search for:

CGRectMake\(([^,]*),([^,]*),([^,]*),([^,]*)\)

which should be replaced by

CGRect\(x:\1, y:\2, w:\3, h:\4\)

Upvotes: -1

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10476

Find by this:

CGRectMake\(([^,]*),([^,]*),([^,]*),([^,]*)\)

and Replace by this:

CGRect\(x:\1, y:\2, w:\3, h:\4\)

Tried it in notepad++

Upvotes: 4

Related Questions