0

I'm completely stumped on how to even proceed with solving this problem. I'm not very good with Obj-C, but I need to create a customized UIButton that will have text on the left side of the button and an image on the right side of the button. The problem is that the text can vary from being 10 characters long to 17 characters long. So, the button needs to resize based on the text length.

The button must have a black background with a corner radius of 12 with white foreground text.

I saw this post on SO: How do I create a custom view class Programmatically?.

This is sort of similar to what I need to do, but I don't understand how to get the "resizable text" part of it to work.

How can I create a custom view where the label and image in the button are configured using constraints?

JFortYork
  • 137
  • 10
  • A button that is positioned using constraints _automatically_ resizes to accomodate a change in its text. So the answer is: do nothing. – matt Jul 20 '20 at 17:19
  • Right, I understand that. But how do you use constraints to setup the button. That is what I want to know. – JFortYork Jul 20 '20 at 17:23
  • Invest some time and read [View Layout](https://developer.apple.com/documentation/uikit/view_layout) & [Autosizing Views for Localization in iOS](https://developer.apple.com/documentation/xcode/autosizing_views_for_localization_in_ios). – zrzka Jul 20 '20 at 19:57

2 Answers2

0

Below may help.

UIFont   *  font = ...    // Button font
CGFloat     zoom = ...    // Zoom factor
NSString * label = ...    // Label text

// Create attributes
NSDictionary * attr = [NSDictionary dictionaryWithObject:
                           [font fontWithSize:font.pointSize * zoom]
                                                  forKey:
                           NSFontAttributeName];

CGSize size = [label sizeWithAttributes:attr];

This may be overkill for what you are looking for at present but if the button becomes more complex this can come in handy. If you do go this route then note there are attributes to control the breaking and paragraph width and so on. Here I just show the font.

skaak
  • 2,988
  • 1
  • 8
  • 16
0

So, I found the answer... there were a few things that were not done correctly:

  1. Make sure the XIB has the correct target membership
  2. The XIB wasn't loading because of a naming conflict (I think). I gave the XIB file and the .h/.m file the XIB file is linked to all the same name.
  3. Made sure that the file owner was linked to the new class
  4. Made sure the outlets were hooked up to the .h file of the new class

After doing these steps, it seems to work.

JFortYork
  • 137
  • 10