-4

I am learning Swift by creating a small quiz app. I need to create a button with few labels (as shown) for the level. Please guide on how to create such type of button. Custom button example

The Level number and progress value is dynamic i.e. will be provided programmatically. Is there a way by which I can create a custom button assign it to a class with outlets for labels, so that I can create an object of the class and assign the values of the label and the entire class behaving as a button i.e. when clicked will move to another view controller showing the questions of that level.

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
aneesh
  • 11
  • 3

1 Answers1

1

You basically answered your own question.

Create a subclass of UIView like so (showing only header file):

@interface MyButton : UIView

@property (nonatomic, weak) IBOutlet UILabel *levelLabel;
@property (nonatomic, weak) IBOutlet UILabel *progressLabel;

@end

Now create a layout file (.xib) with one uiview and uilabels as its children. Set the uiviews class to MyButton and hook up the outlets to the two labels. Remember to set the userInteractionEnabled property of the view to YES.

Use your custom class anywhere in your app by importing "MyButton.h".

EDIT:

In Swift:

class MyButton: UIView {

   @IBOutlet weak var lebelLabel: UILabel?
   @IBOutlet weak var progressLabel: UILabel?

   ...
}

Regarding comment:

I created the xib along with labels and their outlets. Can you please tell how to use and initialise MyButton anywhere.

This has been answered on SO countless times before. For one way of doing it, read here

Community
  • 1
  • 1
oyvindhauge
  • 3,496
  • 2
  • 29
  • 45
  • The creating of xib file option is disabled on specifying subclass of UIView. – aneesh Sep 01 '15 at 15:06
  • File > New > File ... > User Interface > View. Now make this views class MyButton (Do this in Identity Inspector) – oyvindhauge Sep 01 '15 at 15:08
  • Just create the xib separately, then set the class of the view to MyButton, just like you do in Storyboards when setting the ViewController Class. – JMFR Sep 01 '15 at 15:10
  • I created the xib along with labels and their outlets. Can you please tell how to use and initialise `MyButton` anywhere. – aneesh Sep 01 '15 at 15:22
  • Getting a SIGABRT error on `nib.instantiateWithOwner` function. Refer to my question [Getting SIGABRT in custom uiview using xib in Xcode 6 using Swift](http://stackoverflow.com/questions/32354844/getting-sigabrt-in-custom-uiview-using-xib-in-xcode-6-using-swift) – aneesh Sep 02 '15 at 14:26