Previously, we learn how to set events on the UIButton : Handling Button Clicks Events
Now, we will see how to set an image on UIButton. UIButtons have a number of different states. We can set only once the button image for all states but we can assign different values for all the states.
Ok, now we will see how to set images on different states and types:
For setting the ‘default’ image on a button, we can call SetImage method
for UIControlState.Normal and the image you currently set will be used for all states.
Here is the example:
buttonObj = UIButton.FromType (UIButtonType.RoundedRect);
buttonObj.SetImage(UIImage.FromFile ("image.jpg"), UIControlState.Normal);
and also we can make each state different.
On RoundedRect type of button only two states need to be set (when we set the image, we see the blue highlighted color on the button which is generated automatically that is the transparent parts of the image).
For example:
buttonObj= UIButton.FromType(UIButtonType.RoundedRect);
buttonObj.SetImage(UIImage.FromFile ("imageName.jpg"), UIControlState.Normal);
buttonObj.SetImage(UIImage.FromFile ("imageName.jpg"), UIControlState.Disabled);
We can set the separate image for the custom button on the highlighted state, and also if we want to change the look or different image whenever the user will click on the button we can do it by coding like this:
buttonObj = UIButton.FromType(UIButtonType.Custom);
buttonObj.SetImage(UIImage.FromFile ("imageName.jpg"),UIControlState.Normal);
buttonObj.SetImage(UIImage.FromFile ("imageName.jpg "),UIControlState.Highlighted);
buttonObj.SetImage(UIImage.FromFile ("imageName.jpg "),UIControlState.Disabled);
(We can also set the different UIButton states by selecting one by one from the drop-down-list in the Attribute Inspector of the “Interface Builder” on Xcode.)
Leave Comment