Posts tagged #iphone

Create a UIButton in Code with Objective-C

iPhone Button tutorial for Xcode

Create a UIButton Programmatically

When you need more control over the user interface buttons and layout you will need to learn how to create a UIButton in code. Creating a button in code enables dynamic button creation, where you can create buttons in response to panels sliding or context sensitive dialog messages. Understanding code allows you to create interactive and playful interfaces. 

Creating your first button in code can be challenging, you might find yourself in a situation where you don’t see your button. This is a common mistake for developers who are new to the way iOS works with and objects. 

There are 5 important steps that you need to follow when adding any kind of UIView, UIButton, or UILabel programmatically. If you do each of these steps, you will understand how to add any kind of user interface (UI) element to your app.

  1. Create a using the class method buttonWithType:
  2. You need to set text for the button for the current UIControlState.
  3. You need to set the size of the button. 
  4. You need to specify button’s position.
  5. You need to add the button to a visible parent view (i.e. self.view).

If you miss any of these steps, you’ll be staring at a blank screen. You won’t be able to see or touch your button.

Step 1: Create your First iOS 7 UIButton in Code

You can create your first iOS 7 button in code, it will look like the default iOS 7 text buttons using the standard tint color. Open the ViewController.m file and look for the viewDidLoad: method. Add the bold code below to create a button inside the curly braces.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Press Me" forState:UIControlStateNormal];
    [button sizeToFit];
    [self.view addSubview:button];
} 
The default position of a button in code is the top left corner.

The default position of a button in code is the top left corner.

Run the app, and tap the button. 

Did you notice the “Press Me” button is behind the status bar in the top left corner. Sometimes you can’t click the button because it’s behind the status bar. You can fix the bug by setting the center position.

Step 2: Set the Button's Center Position

You can set the center to a new (X, Y) point using the CGPointMake() function. On an iPhone 5 screen your display is 320 points wide and 536 points tall. To get the center X coordinate, divide 320 by 2. Next, use a positive Y value to shift the button downward, you can use 60.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Press Me" forState:UIControlStateNormal];
    [button sizeToFit];

    // Set a new (x,y) point for the button's center
    button.center = CGPointMake(320/2, 60);

    [self.view addSubview:button];
} 
Change the center position to move the button around your iPhone app.

Change the center position to move the button around your iPhone app.

Step 3: Add an action to the button

The button won’t do anything when you tap on it, until you add an action. Define a new method that can be called when the button is tapped. Add it below the viewDidLoad method.

- (void)buttonPressed:(UIButton *)button {
     NSLog(@"Button Pressed");
}

The method buttonPressed: will be called when the button is touched. To be specific it’s a touch inside the bounds of the button. Button presses can be canceled when you drag your finger outside the boundaries of a button, instead of lifting up inside the button. 

To test if it’s working add an NSLog() print statement to show a message on the Console.

You will add a Target/Action pair to the button to give it access to the code file that defines the method and behavior that you want to happen with a button tap. Use the @selector keyword to tell the button the name of the method, including the colon.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Press Me" forState:UIControlStateNormal];
    [button sizeToFit];
    button.center = CGPointMake(320/2, 60);

    // Add an action in current code file (i.e. target)
    [button addTarget:self action:@selector(buttonPressed:)
     forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];
} 

Run the app and tap the button. Now you will see the message in the text Console on the bottom half of Xcode’s window.

The NSLog() function displays text in the Console panel in Xcode.

The NSLog() function displays text in the Console panel in Xcode.

More iPhone Button Customization

You can change the font, text color, and background images for any button on iOS. If you want to learn more, sign up for the iPhone mailing list.

 
Subscribe and you will get FREE access to a 5 video course on custom buttons for iOS.

Subscribe and you will get FREE access to a 5 video course on custom buttons for iOS.

 



Posted on August 5, 2014 and filed under Programming .

You can save so much time using this skill...

There is one thing that I don't teach. I don't teach it because I'm not an expert, but I have a friend, Maxime, who does teach it.

Learning to code is just part of the puzzle when you make an iPhone app. 

If you approach app development without any foundation in design, then you can waste a ton of time and money building the wrong app.

After talking with Maxime, he agreed to provide a great deal on his comprehensive course. Maxime teaches the best-selling course called Mobile App Design from Scratch

If you're developing a mobile app, you need to understand how to design it, and Maxime's class is a great foundation. His course will teach you a complete workflow that will take you from your idea to a fully designed app ready to be coded. 

He'll teach you how to use fantastic design software (not Photoshop!) and all the design concepts you need to know. 

Click here to use the coupon: 

I'll be honest...

I don't promote things that I don't love. 

I LOVE the design tool that Maxime teaches. You can learn about it in his complete design course.

It has been a HUGE time saver in the production of my apps and games and I know that you will appreciate it as much as I have. 

Signup today with this limited discount and you will save time! 

Posted on July 2, 2014 and filed under Design .

Screen Edge Swipe Gesture on iPhone using the UIScreenEdgePanGestureRecognizer Tutorial

 
UIScreenEdge Gesture Recognizer for iPhone Side Swipe Detection

UIScreenEdge Gesture Recognizer for iPhone Side Swipe Detection

 

I was working on updating my app, and I ran into a bug with the new . It doesn't really have much documentation, and didn't behave as I expected.

It's only property is a attribute, but when I set the property to a set of edges (left and right) nothing happened. I thought there were issues with the view hierarchy in my app, so I created this test project. Because it wasn't intuitive and because I didn't see any working code I've posted the project on github so that you can learn how to use it to.

Edge Swipe Demo Video

In my sample view you can see how I can use the x-coordinate to move the entire ViewController's view (iPhone screen) to the left and to the right! It's pretty crazy, check it out here: 

","url":"https://www.youtube.com/watch?v=8KjF0xBotIM&feature=youtu.be","width":640,"height":480,"providerName":"YouTube","thumbnailUrl":"http://i1.ytimg.com/vi/8KjF0xBotIM/hqdefault.jpg","resolvedBy":"youtube"}" data-block-type="32" id="block-fd013a268f33ef95996e">

Edge Swipe Gesture Code

1. Declare an ivar at the top of your ViewController.m file in the top as part of the

#import "ViewController.h"

@interface ViewController ()  {
    CGFloat _centerX;
}
@end

2. Create a UIScreenEdgePanGestureRecognizer in your -viewDidLoad method. Add it to your self.view, so that it will work across the entire iPhone screen.

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIScreenEdgePanGestureRecognizer *leftEdgeGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftEdgeGesture:)];
    leftEdgeGesture.edges = UIRectEdgeLeft;
    leftEdgeGesture.delegate = self;
    [self.view addGestureRecognizer:leftEdgeGesture];

    // Store the center, so we can animate back to it after a slide
    _centerX = self.view.bounds.size.width / 2; 
}

3. Add a new method to handle the gesture and do whatever you want with the translation variable. I only care about the x coordinate, so that's what I'm using in this demo.

- (void)handleLeftEdgeGesture:(UIScreenEdgePanGestureRecognizer *)gesture {
    // Get the current view we are touching
    UIView *view = [self.view hitTest:[gesture locationInView:gesture.view] withEvent:nil];
    
    if(UIGestureRecognizerStateBegan == gesture.state ||
       UIGestureRecognizerStateChanged == gesture.state) {
        CGPoint translation = [gesture translationInView:gesture.view];
        // Move the view's center using the gesture
        view.center = CGPointMake(_centerX + translation.x, view.center.y);
    } else {// cancel, fail, or ended
        // Animate back to center x
        [UIView animateWithDuration:.3 animations:^{
            
            view.center = CGPointMake(_centerX, view.center.y);
        }];
    }
}

4. Conform to the UIGestureRecognizerDelegate delegate protocol (optional). See #1 above on how to conform to the delegate in the .m file using the Class Extension syntax.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    // You can customize the way in which gestures can work
    // Enabling multiple gestures will allow all of them to work together, otherwise only the topmost view's gestures will work (i.e. PanGesture view on bottom)
    return YES;
}

Sample Code on GitHub

Download the sample code and see how quick an easy it is to use it in your iPhone apps.

https://github.com/PaulSolt/UIScreenEdgePanGestureDemo



Posted on March 21, 2014 and filed under Programming .