Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're really asking two questions here, I think: "How do you stretch an image on a button?" and "What do you do when code doesn't work?" I'll take the former first. The following code works for me to create a button from scratch with a stretched image:</p> <pre><code>UIImage *image = [[UIImage imageNamed:@"ButtonPic"] stretchableImageWithLeftCapWidth:19 topCapHeight:19]; CGRect frame = CGRectMake(80, 200, 160, 40); UIButton *button = [[UIButton alloc] initWithFrame:frame]; [button setBackgroundImage:image forState:UIControlStateNormal]; [self.view addSubview:button]; [button release]; </code></pre> <p>You'll need to supply an appropriate image, naturally. My image is a 80x40 px PNG image created in Photoshop, stretched to a width of 160 px above. Here's what it looks like:</p> <p><img src="https://i.stack.imgur.com/H0f6G.png" alt="button screenshot"></p> <p>I don't see any significant differences between my code and <a href="http://books.google.com/books?id=TcP2bgESYfgC&amp;lpg=PA93&amp;ots=dipaKqrQCM&amp;dq=lamarche%20UIButton&amp;pg=PA93#v=onepage&amp;q&amp;f=false" rel="nofollow noreferrer">the code in the book</a>. It looks like the button in the book is loaded from a nib instead of created programmatically, but mine and theirs both call -stretchableImageWithleftCapWidth:topCapHeight: and -setBackgroundImage:forState: to do the relevant work.</p> <p>That brings us to the second question: "What do you do when code doesn't work?"</p> <p>There's not a single answer here, but the first thing to do is narrow the problem as much as you can. Arthur Conan Doyle wrote: <em>"Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth."</em> In a case like this one, where you've just got a few lines of code, an easy way to do that is to isolate the problematic code by copying it into a new project. It only takes a moment to create a new iOS project based on the view template, and you can paste the code above into the -viewDidLoad method of the supplied view controller to try it out. Then all you need to do is to supply an image. If it still doesn't work, you've removed all the other code in your app from suspicion. If it does work, you can gradually add some more code from your app in an attempt to reproduce the problem and identify the cause. Moving your code to a test project isn't always feasible, but you can usually find ways to simplify the problem.</p> <p>As far as errors go, bear in mind that code often fails even when every function and method succeeds. The problem isn't with the components, but with how they're put together.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload