0

I want to programmatically change the dimensions and position of an existing button or label programmatically. The button that I want to edit is already in a ViewController and there are no constraints whatsoever in my app so far.

I have myButton instatiated with:

@IBOutlet var myButton: UIButton!

I've tried:

myButton.frame = CGRectMake(50.0, 50.0, 100.0, 50.0)

and

myButton.frame.origin = CGPoint(x: 10, y: 10)

and

myButton.frame.width = 100

The first two of these lines of code have compiled and ran, but neither have changed any of the dimensions/positions of the button. The third line of code (which I got from here) doesn't even compile because "width is a get only property."

How can I do this?

Community
  • 1
  • 1
Jeffrey Chen
  • 225
  • 3
  • 16

1 Answers1

0

First two lines, especially first one should work, so you may have not connected them with IBOutlet, or if created programatically, may have not been instantiated properly.

While size is one of properties of the frame, you actually need to access this size property. So the third line needs to be updated like this:

myButton.frame.size.width = 100
pedrouan
  • 12,762
  • 3
  • 58
  • 74
  • Your code works and compiles, thanks! But It still isn't updating the button, maybe because it isn't being connected with the IBOutlet? Does the button have to be updated to the IBOutlet again after I instantiate it for the first time? – Jeffrey Chen Sep 02 '16 at 21:55
  • Lets check whether the issue is not only in frame modification. So add one more line under line myButton.frame = ... and the code would be myButton.backgroundColor = UIColor.redColor(). If the color doesn't change, it's definitely not connected properly. To your question: No, just once is needed to make a connection. If you would update your question adding some more pictures of storyboard or code, it could help me understand and solve your issue. – pedrouan Sep 02 '16 at 22:01
  • So I did myButton.backgroundColor = UIColor.redColor() and what happened was that the background of the entire ViewController turned red instead of just the button turning red – Jeffrey Chen Sep 02 '16 at 22:13
  • So we'revery close. I suppose you missed your button whene you connected your IBOutlet and you ctrl dragged your view instead. Don't you? Remove the connection and try to do it again. OR: your button is expanded on the full width of the container view. In case nothing helps, post an image of your storyboard plz – pedrouan Sep 02 '16 at 22:21
  • I checked how the button was connected to the IBOutlet and it wasn't... so I guess I'm just an idiot.... thanks though! – Jeffrey Chen Sep 02 '16 at 22:23
  • It happens very often, it is not so difficult to make a mistake when creating this kind of enviroment, even with solid experience. Happy coding. – pedrouan Sep 03 '16 at 07:11
  • @TheNumberDevil So did my answer help you? :) – pedrouan Oct 01 '16 at 14:01