5

Depending on the height of the screen, I would like to adjust the height of a button in a view. What is the easiest way to do this in Swift?

I tried it in this way and also with CGRectMake() but nothing changed:

self.myButton.frame.size.height = self.myButton.frame.size.height*scrOpt

How can I "update" the frame?

Cuno
  • 89
  • 1
  • 1
  • 7
  • `self.myButton.frame = CGRectMake(self.myButton.frame.origin.x, self.myButton.frame.origin.y, self.myButton.frame..size.width, self.myButton.frame.size.height*scrOpt)` – Chirag D jinjuwadiya May 04 '15 at 09:14
  • 2
    If you are using auto layout, you need to update its height constraint, else update its frame. – Yogesh Suthar May 04 '15 at 09:16
  • See explanation here http://stackoverflow.com/a/16406097/790842. As @YogeshSuthar said, you must be using AutoLayout, and in AutoLayout changing frames doesn't work, you need to work on constraints. – iphonic May 04 '15 at 09:25

2 Answers2

6

The reason why you see no changes may be because you're using AutoLayout, and the button has some constraints applied to it, and you need to change the height constraint to accomplish what you want.

Edited: Changing frame properties directly seems to be possible in Swift but was not possible in Objective C.

pteofil
  • 4,133
  • 17
  • 27
  • 2
    `frame` is not a read-only property, and you *can* assign to `self.myButton.frame.size.height` in Swift ... – Martin R May 04 '15 at 09:28
  • 1
    Yep, that seems the problem - I have AutoLayout on (what seems to work well in general) and try to change this stupid button now in the code... Hmmm... :-/ Thx! – Cuno May 04 '15 at 09:35
  • You're right Martin. I got used to that from Objective C. I edited my answer. – pteofil May 04 '15 at 09:39
0

If you are using auto layout, you need to update its height constraint, else update its frame

NSLog(@"%@",NSStringFromCGRect(self.myButton.frame));

    NSLog(@"%f",scrOpt);

    self.myButton.frame = CGRectMake(self.myButton.frame.origin.x, self.myButton.frame.origin.y, self.myButton.frame.size.width, self.myButton.frame.size.height*scrOpt)

    NSLog(@"%@",NSStringFromCGRect(self.myButton.frame));

Edited check this and see what is Print NSLog