简体   繁体   中英

How to create a custom button design with labels inside it in Xcode 6 using Swift

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. 自定义按钮示例

The Level number and progress value is dynamic ie 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 ie when clicked will move to another view controller showing the questions of that level.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM