Dynamically Modify UI via LLDB expression
Scenario
Assuming you, as an iOS developer, is working on UI components of a app. Your PM comes and taps your shoulder to request color change on a specific button. Usually in this case, developers would be unhappy, because it means he has to go to the codebase to scope the button related code, change its color property, and then rebuild and run the app to verify that color is changed successfully.
It is not a big trouble if such kind of requests are not that frequent. However, PM or designer may still have concerns and ask you to repeatly attempt different colors on the button until they are satisfied with the visual effect.
Do we have to fix code and re-run to check over and over agian? Is there a more effective way to achieve this?
The answer is yes. We can make it without even changing a single line of code. The magic is LLDB expression.
Demo
Let us have a very simple app running on iPhone simulator — just a button on the view. To go to debug mode, we could click the pause button on tool bar:
Then, we could type in following command:
po [[[UIApplication sharedApplication] keyWindow] recursiveDescription]
This command will print out all information related to view hierachy, including its address in memory and its layout.
It tells us the button is 0x7fb0c5f15900. So let’s fetch it from memory:
expression -- id $testView = (id)0x7fb0c5f15900
expression
means executing the following command and print out the result, here we attempt to pass the button to testView.
Now it is good to modify the button’s color. Using expression
command on testView we just fetched:
// set button's color to redexpression -- (void)[$testView setBackgroundColor:[UIColor redColor]]
To witness the change we need to refresh UI by typing the following command:
expression -- (void)[CATransaction flush]
Then you will see the button is changed to red as expected!
Overview
This article just shows one way to handle UI with LLDB expression. LLDB is a powerful tool to enable us to set the button’s text, border, and even navigate to another page.
For expression
command, it is actually the alias of p
and po
; p
is the same as expression --
, while po
is equal to expression -O --
expression . For more usage, try help expression
to find out.