How to put a badge on customized UIBarButtonItem - ios

I have a navigation bar with two buttons, one is a back button the other a chat symbol.
I write this code like this:
UIBarButtonItem *_btn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:#"back.png"]
style:UIBarButtonItemStylePlain
target:self
action:#selector(goBackToPreviousView)];
self.navigationItem.leftBarButtonItem=_btn;
self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
UIBarButtonItem *_btn2=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:#"chat.png"]
style:UIBarButtonItemStylePlain
target:self
action:#selector(startChat)];
self.navigationItem.rightBarButtonItem=_btn2;
self.navigationItem.rightBarButtonItem.tintColor = [Utility colorWithHexValue:CyanBlue];
The problem I have is that whenever there is some new messages in the chat that I have not seen, there should be like a badge of some sort, or a customized label over the chat button, to indicate how many new messages you have.
How do I do this?

for Swift 3.0:
Result:
Code:
override func viewDidLoad() {
super.viewDidLoad()
// badge label
let label = UILabel(frame: CGRect(x: 10, y: -10, width: 20, height: 20))
label.layer.borderColor = UIColor.clear.cgColor
label.layer.borderWidth = 2
label.layer.cornerRadius = label.bounds.size.height / 2
label.textAlignment = .center
label.layer.masksToBounds = true
label.font = UIFont(name: "SanFranciscoText-Light", size: 13)
label.textColor = .white
label.backgroundColor = .red
label.text = "80"
// button
let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 16))
rightButton.setBackgroundImage(UIImage(named: "inbox"), for: .normal)
rightButton.addTarget(self, action: #selector(rightButtonTouched), for: .touchUpInside)
rightButton.addSubview(label)
// Bar button item
let rightBarButtomItem = UIBarButtonItem(customView: rightButton)
navigationItem.rightBarButtonItem = rightBarButtomItem
}
func rightButtonTouched() {
print("right button touched")
}

in iOS 8 - I was able to do it by changing the badgeValue
self.messageButton.badgeValue = #"5";
where message button is a UIBarButton
You have to include these two files to your xcode
UIBarButtonItem+Badge.h
UIBarButtonItem+Badge.m
which can be found here
Github link to files

You can try this piece of code:-
UILabel *badgeLbl = [[UILabel alloc]initWithFrame:CGRectMake(16, -2, 18, 18)];
badgeLbl.backgroundColor = [UIColor whiteColor];
badgeLbl.textColor = [UIColor blackColor];
badgeLbl.textAlignment = NSTextAlignmentCenter;
badgeLbl.layer.cornerRadius = 9.0;
badgeLbl.layer.masksToBounds = true;
badgeLbl.text = #"10";
UIButton *notificationBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
[notificationBtn setBackgroundImage:[UIImage imageNamed:#"image_name"] forState:UIControlStateNormal];
[notificationBtn setTitle:#"" forState:UIControlStateNormal];
[notificationBtn addTarget:self action:#selector(onClickAction:) forControlEvents:UIControlEventTouchUpInside];
[notificationBtn addSubview:badgeLbl];
UIBarButtonItem *notificationBarBtn = [[UIBarButtonItem alloc]initWithCustomView:notificationBtn];
self.navigationItem.rightBarButtonItem = notificationBarBtn;

Good day!
Here is my version - easy and without any problems:
navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 64)];
[self.view addSubview:navBar];
navItem = [[UINavigationItem alloc] initWithTitle:NSLocalizedString(#"Meetings", nil)];
[navBar pushNavigationItem:navItem animated:NO];
UIButton *chat = [UIButton buttonWithType: UIButtonTypeRoundedRect];
[chat setTitle:#"Chat" forState: UIControlStateNormal];
UILabel *badge = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 20, 20)];
badge.textColor = [UIColor darkGrayColor];
badge.font = [UIFont fontWithName: fontName size: 15];
badge.text = #"10";
badge.textAlignment = NSTextAlignmentCenter;
badge.layer.cornerRadius = 10.0f;
badge.layer.backgroundColor = [UIColor yellowColor].CGColor;
badge.clipsToBounds = YES;
badge.center = CGPointMake(50, 20);
[chat addSubview: badge];
navItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: chat];
have a nice day!

try custom methods
https://github.com/TanguyAladenise/BBBadgeBarButtonItem
http://yuvarajmanickam.wordpress.com/2012/02/01/add-badges-on-uibarbuttonitem-in-iphone-app/
How to add Badges on UIBarbutton item?
https://www.cocoacontrols.com/controls/mknumberbadgeview

You can try this category
UIBarButtonItem-Badge

Try this customized control - mknumberbadgeview

Related

Update UIBarButtonItem within view controller

I'm trying to update UIBarButtonItem tint color from a view controller but nothing has changed. Can't we access the UIBarButtonItem within view controller using self.navigationItem.rightBarButtonItem?
[UIView animateWithDuration:.8 delay:0.5 options:UIViewAnimationOptionAllowUserInteraction animations:^ {
//button.alpha = .01; //don't animate alpha to 0, otherwise you won't be able to interact with it
self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
} completion:^(BOOL finished) {
self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
}];
I have tried your problem by making outlet of UIBarButtonItem. It is working fine. You can set the tint color by direct refrence.
Here is the code
class ViewController: UIViewController {
#IBOutlet weak var addItem: UIBarButtonItem!
var username = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func addItem(_ sender: UIBarButtonItem) {
UIView.animate(withDuration: 20) {
self.addItem.tintColor = UIColor.red
}
}
}
let addButton = UIButton(type: .custom)
addButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
addButton.tintColor = UIColor.gray
let addMoreItem = UIBarButtonItem(customView: addButton)
self.navigationItem.rightBarButtonItem = addMoreItem
it may be work for you.
UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[btnback setTintColor:[UIColor whiteColor]];
[btnBack addTarget:self action:#selector(onClickBtnBack:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
self.navigationItem.rightBarButtonItem = barButtonItem;
also you can set background color and text color.

UIPickerView BarButton Text Color is not change but when click on button then the color is change in Objective-C

I have issue I have set UIPickerView BarButton title color to blue but it not give the perfect output but when I click on that button it gives the output means it change the color to blue but I don't want blue color only after click, I want button color blue before click. so how can I do this?
Code:
-(void)SetToolbar
{
//******* add buttons in toolbar
self.toolbar=[[UIToolbar alloc]init];
self.toolbar.autoresizingMask=(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight| UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin );
self.toolbar.frame=CGRectMake(0, self.currencypicker.frame.origin.y, self.currencypicker.frame.size.width, 45);
self.toolbar.barStyle=UIBarStyleDefault;
self.toolbar.backgroundColor=[UIColor whiteColor];
self.toolbar.tintColor=[UIColor blueColor];
UIBarButtonItem *donebutton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(Btn_DoneClick)];
// donebutton.style=UIBarButtonItemStylePlain;
UIBarButtonItem *cancelbutton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(Btn_CancelClick)];
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIView *titleview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 150, 40)];
titleview.backgroundColor=[UIColor clearColor];
UILabel *lbltitle=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, 40)];
lbltitle.backgroundColor=[UIColor clearColor];
lbltitle.textAlignment=NSTextAlignmentCenter;
lbltitle.text=#"Payment Type";
lbltitle.font=[UIFont boldSystemFontOfSize:17.0];
if(IS_IPAD)
{
lbltitle.textColor=[UIColor colorWithRed:113.0/256 green:120.0/256 blue:128.0/256 alpha:1.0];
}
else
{
lbltitle.textColor=[UIColor blackColor];
}
[titleview addSubview:lbltitle];
UIBarButtonItem *btnAdd=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addPaymentClicked)];
UIBarButtonItem *titlebutton = [[UIBarButtonItem alloc] initWithCustomView:titleview];
NSArray *items = [NSArray arrayWithObjects:cancelbutton,flex,titlebutton,flex,btnAdd, donebutton, nil];
[self.toolbar setItems:items animated:NO];
[self.view addSubview:self.toolbar];
[self.view bringSubviewToFront:self.pickerView];
//*******
}
My Delegate DidFinishCode For Navigation:
[[UINavigationBar appearance] setBarTintColor:FooterBGColor];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
if (#available(iOS 11.0, *)) {
[[UINavigationBar appearance] setLargeTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor whiteColor]}];
[[UINavigationBar appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor whiteColor]}];
} else {
}
I know this question was asked 10 months ago. But today I still had this issue. I tried changing tint color and I have no idea why it is not working. After spending hours, I finally decided to create a UIView on UIToolbar and then add a UIButton on it. It worked for me. I hope it might help someone in future.
// UIPickerView
self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
self.myPickerView.delegate = self
self.myPickerView.dataSource = self
self.myPickerView.backgroundColor = UIColor.white
cell.myTextField.inputView = self.myPickerView
// ToolBar
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
// UIView
let myNewView=UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44))
myNewView.backgroundColor = .lightGray
toolBar.addSubview(myNewView)
// UIButton
let button:UIButton = UIButton(frame: CGRect(x: myNewView.bounds.width - 80, y: 0, width: 70, height: 44))
button.setTitle("Done", for: .normal)
button.addTarget(self, action:#selector(self.doneClick), for: .touchUpInside)
myNewView.addSubview(button)
cell.myTextField.inputAccessoryView = toolBar
use tint Color in Donebutton
try This.
UIBarButtonItem *donebutton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(Btn_DoneClick)];
// donebutton.style=UIBarButtonItemStylePlain;
donebutton.tintColor = [UIColor blueColor];

How to make custom UIBarButtonItem with image and label?

I would like to make a custom UIBarButtonItem that contains both image and text, something like this:
I tried subclassing UIBarButtonItem and overriding this method:
- (UIView *)customView
{
if (!self.storedView) {
UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:self.image];
tempImageView.frame = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 100, 44)];
tempLabel.text = #"text";
[temp addSubview:tempImageView];
[temp addSubview:tempLabel];
self.storedView = temp;
}
return self.storedView;
}
And I use it like this:
UIBarButtonItem *left = [[LeftItem alloc] initWithTitle:#"Settings" style:UIBarButtonItemStylePlain target:self action:#selector(settingsPressed)];
left.title = #"Settings";
left.image = [UIImage imageNamed:#"settings.png"];
self.navigationItem.leftBarButtonItem = left;
But using this I only get the image, but not label. What am I doing wrong?
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
[button addTarget:target action:#selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 31)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 50, 20)];
[label setFont:[UIFont fontWithName:#"Arial-BoldMT" size:13]];
[label setText:title];
label.textAlignment = UITextAlignmentCenter;
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[button addSubview:label];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;
You can add a custom view to the UIBarButtonItem.
In iOS 7, there is a new buttonType called UIButtonTypeSystem for UIButton which serve your purpose.
Try this,
UIView* leftButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 50)];
UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
leftButton.backgroundColor = [UIColor clearColor];
leftButton.frame = leftButtonView.frame;
[leftButton setImage:[UIImage imageNamed:<YourImageName>] forState:UIControlStateNormal];
[leftButton setTitle:#"YourTitle" forState:UIControlStateNormal];
leftButton.tintColor = [UIColor redColor]; //Your desired color.
leftButton.autoresizesSubviews = YES;
leftButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
[leftButton addTarget:self action:#selector(<YourTargetMethod>) forControlEvents:UIControlEventTouchUpInside];
[leftButtonView addSubview:leftButton];
UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:leftButtonView];
self.navigationItem.leftBarButtonItem = leftBarButton;
Updated Swift code,
let leftButtonView = UIView.init(frame: CGRect(x: 0, y: 0, width: 110, height: 50))
let leftButton = UIButton.init(type: .system)
leftButton.backgroundColor = .clear
leftButton.frame = leftButtonView.frame
leftButton.setImage(UIImage.init(imageLiteralResourceName: <YourImageName>), for: .normal)
leftButton.setTitle("YourTitle", for: .normal)
leftButton.tintColor = .red //Your desired color.
leftButton.autoresizesSubviews = true
leftButton.autoresizingMask = [.flexibleWidth , .flexibleHeight]
leftButton.addTarget(self, action: #selector(<YourTargetMethod>), for: .touchUpInside)
leftButtonView.addSubview(leftButton)
let leftBarButton = UIBarButtonItem.init(customView: leftButtonView)
navigationItem.leftBarButtonItem = leftBarButton
If your BarButtonItem is in Storyboard, you can drag another Button into BarButtonItem, so there will be a Button inside the BarButtonItem, you can add both image and label to the button.
a SWIFT version
let button = UIButton(type: .Custom)
button.setImage(UIImage(named: "icon_right"), forState: .Normal)
button.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
button.frame = CGRectMake(0, 0, 53, 31)
button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
let label = UILabel(frame: CGRectMake(3, 5, 50, 20))
label.font = UIFont(name: "Arial-BoldMT", size: 16)
label.text = "title"
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.backgroundColor = UIColor.clearColor()
button.addSubview(label)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
Using UIButton as custom view inside your UIBarButtonItem. You can create UIButton however you want, including with an image and text, using -setImage:forState: and -setTitle:forState:
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"settings.png"] forState:UIControlStateNormal];
[button setTitle:#"Settings" forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButtonItem;
this can be done using interface builder just by dragging a UIButton to the left bar button slot on a navigation bar.
The problem with the accepted answer is that the UIBarButtonItem text does not change when highlighted. The code below will display text plus an image. The UIEdgeInsetsMake moves the text to the left and the image to the right.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(myButtonEvent:)
forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 32)];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor]
forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor]
forState:UIControlStateHighlighted];
button.titleEdgeInsets = UIEdgeInsetsMake(-2, -20, 2, 20);
button.titleLabel.font = font;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
UIImage *image = [UIImage imageNamed:#"imageName"];
[button setImage:image
forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32);
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
I posted answer that handles tint colour and image simmilar to normal uibarbuttonitem here... https://stackoverflow.com/a/28348461/925135
Another approach with NSAttributedString:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:#"Button Text"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:#"buttonImage"];
textAttachment.bounds = CGRectMake(0, -3, textAttachment.image.size.width, textAttachment.image.size.height); //the origin y value depends on the size of the image to get a perfect fit
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attrStringWithImage]; // Adding the image at the beginning
[customButton setAttributedTitle:attributedString forState:UIControlStateNormal];
[customButton sizeToFit];
[customButton addTarget:self action:#selector(back:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:customButton];
Here's my solution based on previous answers. May be will be helpful.
extension UIBarButtonItem {
static func button(image: UIImage, title: String, target: Any, action: Selector) -> UIBarButtonItem {
let button = UIButton()
button.setImage(image, for: .normal)
button.addTarget(target, action: action, for: .touchUpInside)
button.setTitle(title, for: .normal)
button.sizeToFit()
return UIBarButtonItem(customView: button)
}
}
UIImage *image = [UIImage imageNamed:#"icon.png"];
UIImage *backgroundSelected = [UIImage imageNamed:#"icon_selected.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(ButtonTapped:event:)forControlEvents:UIControlEventTouchUpInside]; //adding action
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setBackgroundImage:backgroundSelected forState:UIControlStateSelected];
button.frame = CGRectMake(0 ,0,35,35);
then make that button as your custom barbutton
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;
This is the updated version of ripegooseberry's answer for Swift 3
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "icon_right"), for: .normal)
button.addTarget(self, action: Selector(("buttonAction")), for: .touchUpInside)
button.frame = CGRect(x: 0, y: 0, width: 53, height: 31)
button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
let label = UILabel(frame: CGRect(x: 3, y: 5, width: 50, height: 20))
label.font = UIFont(name: "Arial-BoldMT", size: 16)
label.text = "title"
label.textAlignment = .center
label.textColor = UIColor.white
label.backgroundColor = UIColor.clear
button.addSubview(label)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton

How to add Badges on UIBarbutton item?

Hi friends am new to iphone developing. Am struggle with add badge values on UIBarbutton item on right side. I have tried but i can't solve this problem. Can anyone help me.
Thanks in advance!
I know this post is pretty old but with iOS7, MKNumberBadgeView's appearance does not really match the tab bar item badge design.
I have found this other component which herits UIBarButtonItem and do the job very well :
https://github.com/TanguyAladenise/BBBadgeBarButtonItem
Hope this may help other iOS7 developers like me
Finally i found the way to add badges on UIBarbutton item. I searched lot but not found the correct answer. So i created UIButton and add it as a Custom view on rightbarbutton item. Add add the MKNumberBadgeView for display the badge number. Below i have add my code for you.
// Initialize NKNumberBadgeView...
MKNumberBadgeView *number = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(60, 00, 30,20)];
number.value = 10;
// Allocate UIButton
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 70, 30);
btn.layer.cornerRadius = 8;
[btn setTitle:#"Button" forState:UIControlStateNormal];
[btn addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
//[btn setBackgroundColor:[UIColor blueColor]];
[btn setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.1 alpha:0.2]];
btn.font = [UIFont systemFontOfSize:13];
//[btn setFont:[UIFont systemFontOfSize:13]];
[btn addSubview:number]; //Add NKNumberBadgeView as a subview on UIButton
// Initialize UIBarbuttonitem...
UIBarButtonItem *proe = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = proe;
Thanks.
phyzalis has a good answer, there's a categorized version of his solution here:
UIBarButtonItem+Badge
Here's how you can use it:
// Build your regular UIBarButtonItem with Custom View
UIImage *image = [UIImage imageNamed:#"someImage"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0,0,image.size.width, image.size.height);
[button addTarget:self action:#selector(buttonPress:) forControlEvents:UIControlEventTouchDown];
[button setBackgroundImage:image forState:UIControlStateNormal];
// Make BarButton Item
UIBarButtonItem *navLeftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = navLeftButton;
// this is the key entry to change the badgeValue
self.navigationItem.leftBarButtonItem.badgeValue = #"1";
I did something similar to MaxMa, but I just went ahead and added the badge directly to the self.navigationController.navigationBar.
MKNumberBadgeView *numberBadge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(35, 0, 40, 40)];
numberBadge.value = 1;
[self.navigationController.navigationBar addSubview:numberBadge];
Just make sure to remove it from the subview during viewWillDisappear and add it back during viewDidAppear. It still seems a little hacky, but I'm more comfortable with this hack then changing the nav bar z-order.
To remove it during viewWillDisappear
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[numberBadge removeFromSuperview];
}
It's simple and the best way !
MKNumberBadgeView *numberBadge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(230, -51, 40, 40)];
numberBadge.value = 5;
self.navigationController.navigationBar.layer.zPosition = -1;
[self.view addSubview:numberBadge];
Updated for Swift 3:
use below simple code to add the badge on UIBarButtonItem;
// Variable Declartion
var badgeCount = Int()
// Instance Method
func setUpBadgeCountAndBarButton() {
// badge label
let label = UILabel(frame: CGRect(x: 10, y: -05, width: 25, height: 25))
label.layer.borderColor = UIColor.clear.cgColor
label.layer.borderWidth = 2
label.layer.cornerRadius = label.bounds.size.height / 2
label.textAlignment = .center
label.layer.masksToBounds = true
label.textColor = .white
label.font = label.font.withSize(12)
label.backgroundColor = .red
label.text = "\(self.badgeCount)"
// button
let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
rightButton.setBackgroundImage(UIImage(named: "notification_dash"), for: .normal)
rightButton.addTarget(self, action: #selector(notificationBarButtonClick), for: .touchUpInside)
rightButton.addSubview(label)
// Bar button item
let rightBarButtomItem = UIBarButtonItem(customView: rightButton)
navigationItem.rightBarButtonItem = rightBarButtomItem
}
// Call To Method
self.badgeCount = 11
self.setUpBadgeCountAndBarButton()
//Note: Increase your badge as per you received notification.You have to write your code as per your decided your logic i.e. how to maintain that badge count number in database.
Enjoy..!
I know this has been solved already,but I thought I might add what I have discovered to this answer for the sake of completeness.
You can also just add MKNumberBadgeView directly to the view for the UIBarButtonItem. Using Monotouch (C#), this is how you get the view for the UIBarButtonItem
//barbutton is some UIBarButtonItem. Make sure to check for view. In
//ViewDidLoad(), the view for the barbutton might not exist yet.
Selector sel = new Selector("view");
var handle = Messaging.intptr_objc_msgSend(barbutton.Handle, sel.Handle);
var view = Runtime.GetNSObject(handle) as UIView;
var mkBadge = ... //the badge
view.Add(badge);
view.Layer.ZPosition = <some large number>
I'm sure it's easy to convert this to Obj-C. You will also need to play around with the Frame for the badge to get it to show up in the right place.
This way you wont have to remove/add the view from the navigationbar.
After searching too many solutions I found this best solution for Objective-C
Goto Following Link and download two files "UIBarButtonItem+Badge.h" and "UIBarButtonItem+Badge.m" and add to your project :
https://github.com/mikeMTOL/UIBarButtonItem-Badge
Then import in your class :
#import "UIBarButtonItem+Badge.h"
And write down following line to add badge :
self.navigationItem.rightBarButtonItem.badgeValue = #"1"; //your value
Hope it will Work !!!
Here is a simple Swift 4 solution for it (with some customisation) https://github.com/Syngmaster/BadgedBarButtonItem
Just drag and drop the class into your project and you can use it like that:
class ViewController: UIViewController {
let btn = BadgedButtonItem(with: UIImage(named: "your_image"))
override func viewDidLoad() {
super.viewDidLoad()
btn.badgeTextColor = .black
btn.badgeTintColor = .yellow
btn.position = .right
btn.hasBorder = true
btn.borderColor = .red
btn.badgeSize = .medium
btn.badgeAnimation = true
self.navigationItem.rightBarButtonItem = btn
btn.tapAction = {
self.btn.setBadge(with: 4)
}
}
}
Extension to add an UIActivityIndicatorView without replacing the UIBarButtonItem.
extension UIBarButtonItem {
func startLoading() {
guard let view = self.value(forKey: "view") as? UIView else { return }
let loading = UIActivityIndicatorView(activityIndicatorStyle: .gray)
loading.frame = view.bounds
loading.startAnimating()
view.addSubview(loading)
view.bringSubview(toFront: loading)
let buttonView = view.subviews.first
buttonView?.alpha = 0.1
}
func stopLoading() {
guard let view = self.value(forKey: "view") as? UIView else { return }
let loading = view.subviews.filter({ $0 is UIActivityIndicatorView }).first
loading?.removeFromSuperview()
let buttonView = view.subviews.first
buttonView?.alpha = 1.0
}
}

How do I create a basic UIButton programmatically?

How can I create a basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, three UIButtons will be created dynamically and its layout or properties are set.
Here's one:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Objective-C
UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
[but addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[but setFrame:CGRectMake(52, 252, 215, 40)];
[but setTitle:#"Login" forState:UIControlStateNormal];
[but setExclusiveTouch:YES];
// if you like to add backgroundImage else no need
[but setbackgroundImage:[UIImage imageNamed:#"XXX.png"] forState:UIControlStateNormal];
[self.view addSubview:but];
-(void) buttonClicked:(UIButton*)sender
{
NSLog(#"you clicked on button %#", sender.tag);
}
Swift
let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
myButton.setTitle("Hai Touch Me", forState: .Normal)
myButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
myButton.frame = CGRectMake(15, 50, 300, 500)
myButton.addTarget(self, action: "pressedAction:", forControlEvents: .TouchUpInside)
self.view.addSubview( myButton)
func pressedAction(sender: UIButton!) {
// do your stuff here
NSLog("you clicked on button %#", sender.tag)
}
Swift3 and above
let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
myButton.setTitle("Hi, Click me", for: .normal)
myButton.setTitleColor(UIColor.blue, for: .normal)
myButton.frame = CGRect(x: 15, y: 50, width: 300, height: 500)
myButton.addTarget(self, action: #selector(pressedAction(_:)), for: .touchUpInside)
self.view.addSubview( myButton)
func pressedAction(_ sender: UIButton) {
// do your stuff here
print("you clicked on button \(sender.tag)")
}
SwiftUI
for example you get the step by step implemntation from SwiftUI Developer portal
import SwiftUI
struct ContentView : View {
var body: some View {
VStack {
Text("Target Color Black")
Button(action: {
/* handle button action here */ })
{
Text("your Button Name")
.color(.white)
.padding(10)
.background(Color.blue)
.cornerRadius(5)
.shadow(radius: 5)
.clipShape(RoundedRectangle(cornerRadius: 5))
}
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
- (void)viewDidLoad {
[super viewDidLoad];
[self addMyButton]; // Call add button method on view load
}
- (void)addMyButton{ // Method for creating button, with background image and other properties
UIButton *playButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
playButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
[playButton setTitle:#"Play" forState:UIControlStateNormal];
playButton.backgroundColor = [UIColor clearColor];
[playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:#"blueButton.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:#"whiteButton.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[playButton addTarget:self action:#selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];
}
To add a button programatically to your controller's view, use the following:
-(void)viewDidLoad
{
UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 50);
[btn setTitle:#"Hello, world!" forState:UIControlStateNormal];
[self.view addSubview:btn];
}
To add three of these, rinse and repeat.
Here you can create dynamically a UIButton:
//For button image
UIImage *closebtnimg = [UIImage imageNamed:#"close_btn.png"];
//Custom type button
btnclose = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
//Set frame of button means position
btnclose.frame = CGRectMake(103, 257, 94, 32);
//Button with 0 border so it's shape like image shape
[btnclose.layer setBorderWidth:0];
//Set title of button
[btnclose setTitle:#"CLOSE" forState:UIControlStateNormal];
[btnclose addTarget:self action:#selector(methodname:) forControlEvents:UIControlEventTouchUpInside];
//Font size of title
btnclose.titleLabel.font = [UIFont boldSystemFontOfSize:14];
//Set image of button
[btnclose setBackgroundImage:closebtnimg forState:UIControlStateNormal];
Come on, it's 2014! Why isn't code block evaluation assignment being used yet, as trends show it's the future!
UIButton* button = ({
//initialize button with frame
UIButton* button = [[UIButton alloc] initWithFrame:({
CGRect frame = CGRectMake(10.0, 10.0, 200.0, 75.0);
frame;
})];
//set button background color
[button setBackgroundColor:({
UIColor* color = [UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0];
color;
})];
//set button title for state
[button setTitle:({
NSString* string = [NSString stringWithFormat:#"title words"];
string;
}) forState:({
UIControlState state = UIControlStateNormal;
state;
})];
//set selector
[button addTarget:self action:({
SEL select = #selector(method:);
select;
}) forControlEvents:({
UIControlEvents event = UIControlEventTouchUpInside;
event;
})];
//return button
button;
});
[self.view addSubview:button];
whoa!
Or the exact results can be accomplished as such:
UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 10.0, 200.0, 75.0)];
[button setBackgroundColor:[UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0]];
[button setTitle:#"title words" forState:UIControlStateNormal];
[button addTarget:self action:#selector(method:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
'action:#selector(aMethod:)' write method like this :
- (void)aMethod:(UIButton*)button
{
NSLog(#"Button clicked.");
}
It works for me. Thanks. KS.
Objective-C
// Create the Button with RoundedRect type
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// instend of "Click Me" you can write your own message/Label
[mybutton setTitle:#"Click Me" forState:UIControlStateNormal];
// create the Rectangle Frame with specified size
mybutton.frame = CGRectMake(10, 10, 300, 140); // x,y,width,height [self.view addSubview:mybutton];// add button to your view.
Swift
let button = UIButton(type: UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
self.view.addSubview(button)
try this code to create a button and repeat it for 2 more times with different coordinates and the method(myButtonClick) is called when the button is pressed
UIButton *editButton = [UIButton buttonWithType: UIButtonTypeCustom];
editButton.frame = CGRectMake(0, 0, width, height);
[editButton setBackgroundImage: editButtonImage forState: UIControlStateNormal];
[myButton addTarget:self action:#selector(myButtonClick:) forControlEvents:UIControlEventTouchUpInside];
editButton.adjustsImageWhenHighlighted = YES;
editButton.titleLabel.text = #"Edit";
editButton.titleLabel.textColor = [UIColor whiteColor];
editButton.titleLabel.textAlignment = UITextAlignmentCenter;
editButton.titleLabel.font = [UIFont fontWithName: #"Helvetica" size: 14];
[self.view addSubview: editButton];
-(void) myButtonClick:(NSString *)myString{
NSLog(#"you clicked on button %#", myString);
}
Check out this code:
Swift 4.2
let frameimg = CGRect(x: 15, y: 46, width: 55, height: 70)
let btnTest = UIButton(type: .roundedRect)
btnTest.frame = frameimg
btnTest.tag = 11
btnTest.setTitle("Test Button", for: .normal)
btnTest.addTarget(self, action: #selector(self.buttonAction(sender:)), for: .touchUpInside)
btnTest.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12.0)
btnTest.titleLabel?.lineBreakMode = .byWordWrapping
btnTest.titleLabel?.numberOfLines = 2
btnTest.titleLabel?.textAlignment = .center
btnTest.setTitleColor(UIColor.gray, for: .normal)
btnTest.setTitleColor(UIColor.blue, for: .selected)
btnTest.showsTouchWhenHighlighted = true
view.addSubview(btnTest)
Objective C
CGRect frameimg = CGRectMake(15, 46, 55,70);
UIButton *SelectionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
SelectionButton.frame=frameimg;
SelectionButton.tag=i;
[SelectionButton setTitle:[SelectionArray objectAtIndex:0] forState:UIControlStateNormal];
[SelectionButton addTarget:self action:#selector(BtnSelected:)
forControlEvents:UIControlEventTouchUpInside];
[SelectionButton.titleLabel setFont:[UIFont boldSystemFontOfSize:12.0]];
SelectionButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
SelectionButton.titleLabel.numberOfLines = 2;
SelectionButton.titleLabel.textAlignment = NSTextAlignmentCenter;
[SelectionButton setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
[SelectionButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[SelectionButton setShowsTouchWhenHighlighted:YES];
[self.view addSubview:SelectionButton];
I hope this code will work for you.
You can just put the creator instance within a loop and dynamically add names from an array if you so wish.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(10.0, 100.0, 300.0, 20.0);
[self.view addSubview:button];
-(UIButton *)addButton:(NSString *)title :(CGRect)frame : (SEL)selector :(UIImage *)image :(int)tag{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = frame;
[btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:title forState:UIControlStateNormal];
[btn setImage:image forState:UIControlStateNormal];
btn.backgroundColor = [UIColor clearColor];
btn.tag = tag;
return btn;
}
and you can add it to the view:
[self.view addSubview:[self addButton:nil :self.view.frame :#selector(btnAction:) :[UIImage imageNamed:#"img.png"] :1]];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
This is an example as well to create three buttons. Just move their location.
UIImage *buttonOff = [UIImage imageNamed:#"crysBallNorm.png"];
UIImage *buttonOn = [UIImage imageNamed:#"crysBallHigh.png"];
UIButton *predictButton = [UIButton alloc];
predictButton = [UIButton buttonWithType:UIButtonTypeCustom];
predictButton.frame = CGRectMake(180.0, 510.0, 120.0, 30.0);
[predictButton setBackgroundImage:buttonOff forState:UIControlStateNormal];
[predictButton setBackgroundImage:buttonOn forState:UIControlStateHighlighted];
[predictButton setTitle:#"Predict" forState:UIControlStateNormal];
[predictButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
[predictButton addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:predictButton];
You can create button by this code.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:self action:#selector(btnAction) forControlEvents:UIControlEventTouchDragInside];
[btn setTitle:#"click button" forState:UIControlStateNormal];
btn.frame = CGRectMake(50, 100, 80, 40);
[self.view addSubview:btn];
Here is the button action method
-(void)btnAction
{
NSLog(#"button clicked");
}
For Swift 2.0:
let btnObject : UIButton = UIButton()
btnObject.frame = CGRect(x: 8, y: 89, width: 70, height: 22)
btnObject.titleLabel?.font = UIFont(name: "Helvetica Neue", size: 13)
btnObject.titleLabel?.textColor = UIColor.whiteColor()
btnObject.backgroundColor = UIColor(red: 189/255, green: 176/255, blue: 0/255, alpha: 1)
btnObject.titleLabel?.textAlignment = NSTextAlignment.Center
btnObject.addTarget(self, action: "btnbtnObjectClick:", forControlEvents: UIControlEvents.TouchUpInside)
subView.addSubview(btnObject)
For creating UIButton programmatically we can create in both objective c and swift
SWIFT 3
let buttonSwift = UIButton(type: UIButtonType.system) as UIButton
//OR
let buttonSwift = UIButton(type: UIButtonType.Custom) as UIButton
//Set Frame for Button
buttonSwift.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
//Set title for button
buttonSwift.setTitle("ClickMe", for: .normal)
//If you want to set color for button title
buttonSwift.setTitleColor(UIColor.white, for: .normal)
//If you want to set Background color for button
buttonSwift.backgroundColor = UIColor.black
//If you want to set tag for button
buttonSwift.tag = 0
//If you want to add or set image for button
let image = UIImage(named: "YourImageName") as UIImage?
buttonSwift.setImage(image, for: .normal)
//If you want to add or set Background image for button
buttonSwift.setBackgroundImage(image, for: .normal)
//Add action for button
buttonSwift.addTarget(self, action: #selector(actionPressMe), for:.touchUpInside)
//Add button as SubView to Super View
self.view.addSubview(buttonSwift)
UIButton Action Method
func actionPressMe(sender: UIButton!)
{
NSLog("Clicked button tag is %#", sender.tag)
OR
print("Clicked button tag is \(sender.tag)")
//Then do whatever you want to do here
........
}
OBJECTIVE C
UIButton *buttonObjectiveC = [UIButton buttonWithType:UIButtonTypeCustom];
OR
UIButton *buttonObjectiveC = [UIButton buttonWithType:UIButtonTypeSystem];
buttonObjectiveC.frame = CGRectMake(200, 100, 200, 100);
//Set title for button
[buttonObjectiveC setTitle:#"ClickMe" forState:UIControlStateNormal];
//If you want to set color for button title
[buttonObjectiveC setTitleColor:[UIColor whiteColor] forState: UIControlStateNormal];
//If you want to set Background color for button
[buttonObjectiveC setBackgroundColor:[UIColor blackColor]];
//If you want to set tag for button
buttonSwift.tag = 0;
//If you want to add or set image for button
UIImage *image = [UIImage imageNamed:#"YourImageName"];
[buttonObjectiveC setImage:image forState:UIControlStateNormal];
//If you want to add or set Background image for button
[buttonObjectiveC setBackgroundImage:image forState:UIControlStateNormal];
//Add action for button
[buttonObjectiveC addTarget:self action:#selector(actionPressMe:)forControlEvents:UIControlEventTouchUpInside];
//Add button as SubView to Super View
[self.view addSubview:buttonObjectiveC];
UIButton Action Method
- (void)actionPressMe:(UIButton *)sender
{
NSLog(#"Clicked button tag is %#",sender.tag);
//Then do whatever you want to do here
..........
}
Output Screenshot is
Try it....
UIButton *finalPriceBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
finalPriceBtn.frame=CGRectMake(260, 25, 45, 15);
[finalPriceBtn addTarget:self action:#selector(goBtnClk:) forControlEvents:UIControlEventTouchUpInside];
finalPriceBtn.titleLabel.font=[UIFont systemFontOfSize:12];
[finalPriceBtn setTitle:[NSString stringWithFormat:#"$%.2f",tempVal] forState:UIControlStateNormal];
finalPriceBtn.titleLabel.textColor = [UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f alpha:1];
finalPriceBtn.titleLabel.textAlignment=UITextAlignmentLeft;
[imageView addSubview:finalPriceBtn];
Hope i helped.
-(void)addStuffToView
{
UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 20, 20)]; //(x, y, width, height of button on screen
[aButton setTitle:#"Button" forState:UIControlStateNormal];//puts the text on the button
aButton.titleLabel.font = somefont;//sets the font if one is already stated
aButton.titleLabel.font = [UIFont fontWithName:#"Arial-MT" size:12];//sets the font type and size
[aButton addTarget:self action:#selector(back) forControlEvents:UIControlEventTouchUpInside];//see back method below
[aButton setBackgroundImage:[UIImage imageNamed:#"someImage.png"] forState:UIControlStateNormal];//sets the image of the button
[self.view addSubview:back];
}
-(void)back
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle.....]
}
-(void)viewDidLoad
{
[super viewDidLoad];
[self addStuffToView];//adds all items built in this method to the view
}
For Swift 2.2 (with the with the new "selector" declaration).
let btn = UIButton(type: UIButtonType.System) as UIButton
btn.frame = CGRectMake(0, 0, 100, 20) // set any frame you want
btn.setTitle("MyAction", forState: UIControlState.Normal)
btn.addTarget(self, action: #selector(MyClass.myAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
func myAction(sender:UIButton!){
// Some action
}
You can implement it in your ViewDidLoad Method:
continuebtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 100, view1.frame.size.width-20, 40)];
[continuebtn setBackgroundColor:[UIColor grayColor]];
[continuebtn setTitle:#"Continue" forState:UIControlStateNormal];
continuebtn.layer.cornerRadius = 10;
continuebtn.layer.borderWidth =1.0;
continuebtn.layer.borderColor = [UIColor blackColor].CGColor;
[continuebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[continuebtn addTarget:self action:#selector(continuetonext) forControlEvents:UIControlEventTouchUpInside];
[view1 addSubview:continuebtn];
Where continuetonext is:
-(void)continuetonext
{
GeneratePasswordVC *u = [[GeneratePasswordVC alloc]init];
[self.navigationController pushViewController:u animated:YES];
}
As of Swift 3, several changes have been made to the syntax.
Here is how you would go about creating a basic button as of Swift 3:
let button = UIButton(type: UIButtonType.system) as UIButton
button.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
button.backgroundColor = UIColor.green
button.setTitle("Example Button", for: UIControlState.normal)
self.view.addSubview(button)
Here are the changes that have been made since previous versions of Swift:
let button = UIButton(type: UIButtonType.System) as UIButton
// system no longer capitalised
button.frame = CGRectMake(100, 100, 100, 50)
// CGRectMake has been removed as of Swift 3
button.backgroundColor = UIColor.greenColor()
// greenColor replaced with green
button.setTitle("Example Button", forState: UIControlState.Normal)
// normal is no longer capitalised
self.view.addSubview(button)
UIButton *custombutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[custombutton addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[custombutton setTitle:#"Click" forState:UIControlStateNormal];
custombutton.frame = CGRectMake(80.0, 110.0, 160.0, 40.0);
custombutton.titleLabel.textColor = [UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f alpha:1];
[custombutton setImage:[UIImage imageNamed:#"hh.png"] forState:UIControlStateNormal];
[view addSubview:custombutton];
try this:
first write this in your .h file of viewcontroller
UIButton *btn;
Now write this in your .m file of viewcontrollers viewDidLoad.
btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
[btn setTitle: #"My Button" forState:UIControlStateNormal];
[btn setTitleColor: [UIColor blueVolor] forState:UIControlStateNormal];
[btn.layer setBorderWidth:1.0f];
[btn.layer setBorderColor:[UIColor BlueVolor].CGColor];
//adding action programatically
[btn addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
write this outside viewDidLoad method in .m file of your view controller
- (IBAction)btnClicked:(id)sender
{
//Write a code you want to execute on buttons click event
}
For Swift 3 (even shorter code)
let button = UIButton(type: UIButtonType.custom)
button.frame = CGRect(x: 0, y: 0, width: 200.0, height: 40.0)
button.addTarget(nil, action: #selector(tapButton(_:)), for: UIControlEvents.touchUpInside)
button.tintColor = UIColor.white
button.backgroundColor = UIColor.red
button.setBackgroundImage(UIImage(named: "ImageName"), for: UIControlState.normal)
button.setTitle("MyTitle", for: UIControlState.normal)
button.isEnabled = true
func tapButton(sender: UIButton) {
}
UIButton *buttonName = [UIButton
buttonWithType:UIButtonTypeRoundedRect];
[buttonName addTarget:self
action:#selector(aMethod:)forControlEvents:UIControlEventTouchDown];
[buttonName setTitle:#"Show View" forState:UIControlStateNormal];
.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); [view
addSubview:buttonName];
In Swift 5 and Xcode 10.2
Basically we have two types of buttons.
1) System type button
2) Custom type button (In custom type button we can set background image for button)
And these two types of buttons has few control states https://developer.apple.com/documentation/uikit/uicontrol/state
Important states are
1) Normal state
2) Selected state
3) Highlighted state
4) Disabled state etc...
//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
// button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
// button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)
#objc func buttonClicked(sender:UIButton) {
print("Button \(sender.tag) clicked")
}
//You can add UIButton properties using extension
extension UIButton {
func btnProperties() {
layer.cornerRadius = 10//Set button corner radious
clipsToBounds = true
backgroundColor = .blue//Set background colour
//titleLabel?.textAlignment = .center//add properties like this
}
}
The Swift 3 version should be:
let myButton:UIButton = {
let myButton = UIButton() // If you want to set the type use like
// UIButton(type: .RoundedRect) or
// UIButton(type: .Custom)
myButton.setTitle("Hai Touch Me", for: .normal)
myButton.setTitleColor(UIColor.blue, for: .normal)
myButton.frame = CGRect(x: 20, y: 20, width: 100, height: 40)
myButton.addTarget(self, action: #selector(ViewController.pressedAction(_:)), for: .touchUpInside)
self.view.addSubview(myButton)
return myButton
}()
UIButton *btnname = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnname setTitle:#"Click Me" forState:UIControlStateNormal];
btnname.frame = CGRectMake(10, 10, 100, 140);
[self.view addSubview:btnname];

Resources