ios8,uibutton,autolayout,uikit,uistoryboard , Label on UIButton not laid out correctly with autolayout

Label on UIButton not laid out correctly with autolayout


Tag: ios8,uibutton,autolayout,uikit,uistoryboard

I have an app which I'm updating to auto layout and size classes and I'm getting some weird behaviour with the label on a button.

The button should be a circle and have a label in the centre. I'm implementing my own subclass so I can reuse it.

Here's the storyboard:


Storyboard 2

and the code for the class which extends UIButton:

- (id)initWithCoder:(NSCoder *)aDecoder
    self = [super initWithCoder:aDecoder];

    if (self) {
        [self setBackgroundImage:[UIImage imageNamed:@"selected-green"] forState:UIControlStateHighlighted                                                                                                                                                                                               ];

        self.layer.borderColor = [UIColor tlbWhiteColor].CGColor;
        self.layer.borderWidth = 10;

    return self;

-(void) layoutSubviews {
    self.layer.cornerRadius = self.frame.size.width / 2;

With this the appears as expected but there is no label. On debugging I see that the frame of the label has 0 height and width. So I extended layoutSubviews:

-(void) layoutSubviews {
    self.layer.cornerRadius = self.frame.size.width / 2;
    if (self.titleLabel.frame.size.width == 0) {
        [self.titleLabel sizeToFit];
        [self setNeedsLayout];
        [self layoutIfNeeded];


The label then appears, but it's in the wrong place:


The only extra info I can offer is that in Reveal the button has weird height and width constraints added:


The titleInsets are all at 0.

Help hugely appreciated.


Ok, this was a real school boy error.

When the docs said 'The implementation of this method is empty before iOS 6' I for some reason took this to mean there's no need to call super on layoutSubviews.

So the fix was:

-(void) layoutSubviews {
    [super layoutSubviews];  // <<<<< THIS WAS MISSING
    self.layer.cornerRadius = self.frame.size.width / 2;
    self.layer.masksToBounds = YES;


Using tags in Swift

I have about 15 UIButtons in my controller. Im trying to clear 10 of them with a simple for loop and looks like I am getting some kind of conflict. When I hit the button to clear, I get the following error: Could not cast value of type '_UISizeTrackingView' (0x18a023c)...

Cannot invoke 'canEvaluatePolicy' with an argument list of type '(LAPolicy)' Swift2.0 Xcode 7

I have a problem with canEvaluatePolicy function. I have declared this function like this : func canEvaluatePolicy(policy: LAPolicy) { do { try authenticationObject.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics) } catch let error as NSError { print("Error: \(error.domain)") } } But when I want to use it like this: if authenticationObject.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics) { I have an error:...

How to i create new arrays using swift?

I'm not exactly sure what I am looking for, so I'm just going to give you an example... Inside App Lets say I am making a shopping list app. In the app, you can create as many shopping lists as you like, and in those shopping lists, you can add...

Why does didUpdateLocations: only have one location after locationManagerDidResumeLocationUpdates:

I have location services working in iOS8. It is set for kCLLocationAccuracyBest using startMonitoringSignificantLocationChanges to restart when in the background and startUpdatingLocation for accuracy. When I set pausesLocationUpdatesAutomatically = YES, the location services get paused and resumed as expected. However, the following call to didUpdateLocations: only has one location in...

How do I set the UISearchController's searchBar to a view that isn't the tableHeaderView or navigationItem.titleview?

I'm trying to keep the search bar in view as the table scrolls. At the moment I'm placing it as the header in a tableview, and it works as it should, but of course the search bar scrolls off screen as you go down the table. I thought I could...

iOS 8 Autolayout - Visual Format Language how to add constraint to superview's edge

Can I pin my view to my superView's edge instead of its layout margin through VFL? Can I be even flexible to toggle "Relative to margin" on myView as well? NO VFL (this is what I want to achieve with Visual Format Language): var constraintLeft = NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.Left,...

Move UIToolbar with keyboard iOS8

I have a UIToolbar at the bottom of my ViewController that is inherited from the self.navigationController. I show it in my ViewController in the viewWillAppear: method using this code: [self.navigationController setToolbarHidden:NO animated:NO]; self.navigationController.toolbar.backgroundColor = [UIColor blackColor]; self.navigationController.toolbar.tintColor = [UIColor blackColor]; self.navigationController.toolbar.barStyle = UIBarStyleBlackOpaque; After that, my ViewController has both programmatically...

UIButton with single press and long press events swift

I want to trigger two action on button click and button long click. I have add a UIbutton in my interface builder. How can i trigger two action using IBAction can somebody tell me how to archive this ? this is the code i have used for a button click...

create a popup window with just a textview/string and a button SWIFT ios 8

I am very new to ios 8 and swift but I have not found a way to make a simple popup window whenever a button is pushed. I payed for tutorials and they still don't cover it. All i would like is for when the user pushes a button (the...

Pass data from one view controller to the next WITHOUT a segue in swift

So I have an app that where you choose a button in the first screen it will bring you to another screen depending on which one you chose on the first one. Because I have these possible different layouts I can't just use a segue from one button to the...

Test-Flight App beta testing time limitations

I need to submit my binary files over the air without pushing app to app-store. one solution is using enterprise program, Test-Flight App Beta Testing we can send binary files to external users to limit of 1000. My Questions is : will apple take beta review (following apple guidelines) of...

Swipe up to show button in UITableView?

I'd like to place a button at the top of a UITableView or UICollectionView, but only shown when swiped up beyond the first row. Usually you see scroll to refresh or a search bar there, but I'd like to put a button there for another functionality. How can I do...

Fatal error when unwrapping CLLocation Location Coordinate

I currently have a test application to teach myself Core Location. It is an app with a button which will either show your location when you press a button, or an alert when location services are off. I get a fatal error (unexpectedly found nil when unwrapping option value) When...

Using the device simulator for iOS 8 with Xcode 7

I thinking about port my App to Swift 2 and Xcode 7. But the device simulator only targets iOS 9 and I see no way to download iOS 8. I have parallel Xcode 6.3 installed. Is there any way to test and debug my app under iOS 8 with the...

Calling prepareforSegue from a UIButton?

I am trying to call a prepareForSegue function out of TableViewController from a button in an UITableViewCell. Can I just call it from the button? Something like: TableViewcontroller: func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "segueExercise") { print(segue.identifier) let vc = segue.destinationViewController as! DetailViewController TableViewCell: @IBAction func exerciseAction(sender:...

iOS 8 Swift 1.2 and Parse - Attempt to present UIAlertController on ViewController whose view is not in the window hierarchy

There are many questions on Stack concerning this issue, but none of them seem to solve the issue I'm having. I am using ParseUI for the login and signup portion of my application. What I would like to have happen is for a UIAlertController to be presented when a user...

When building to mobile the size of fonts reduce and became very small

Like I said in the title when i built to mobile the letter became too small. I think it is because phone has more pixel for his little screen. Well I tried to fix text by simply making text to images in photoshop. But how can I make InputFields text...

Opening and closing form animation

Is this animation possible in iOS, any third party API's for that? ...

Update button image on swift 2.0

When I try using this solution to update an UIButton image (Xcode 7 beta 1), it gives me this error: "Cannot invoke 'setImage' with an argument list of type '(UIImage?, forState: nil)'" Here's the code: if counter % 2 == 0{ playButton.setImage(UIImage(named: "pause"), forState: nil) } else if counter %...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

A Plugin to view PDF document in iOS cordova based application

Can please suggest a working plugin to view PDF in iOS Cordova based application. I have tried many of PDF related plugins: but of no use..My application stopped at loading. Lastly with I have tried with pebois/phonegap-plugin-PDFViewer: I have installed using : "cordova plugin add com.lesfrancschatons.cordova.plugins.pdfreader" In index.html:...

Wikitude does not work. Poi do not change the position on phone position change

I am trying to integrate AR poi view with Wikitude in my app. As html I used a file from the example 4_PointOfInterest_4_SelectingPois. It should render a few point around my location. It does it, but all points stay in the same position all the time, although I changed my...

Bluemix authentication ios8 with google and facebook

I am trying to implement two types of authentication from an iOS8 device in the bluemix platform. I succeeded in adding one type of authentication: google. I am using a ADVANCED MOBILE ACCESS module, and I am at the User Authentication part. It looks from a dashboard like I can...

UIButton with pushViewController that is declared in another class

Hi everyone I am trying to add a custom nav bar that is declared in a different class and has a button that make a push action. My initial problem was that when the app was pushing the view because of the uinavicgationconreoller it was crashing, I fixed that somehow...

Core Location and UITableView performance issues in iOS 8

I have a view controller that contains two views: a map view using the Google Maps API and a UITableView. The view controller fetches a list of location objects from Google Maps within a certain radius of a particular location and plots them on the map view as markers and...

Autolayout works great on iOS 8, crashes on iOS 7

I have an issue where a screen with autolayout that works great on iOS 8 - but crashes on iOS 7. All subviews are configured in the XIB. The error message is: Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view. Does the constraint reference...

Getting error in Adjust library, Integrated with Pods

I am getting this error: ld: library not found for -lPods-Adjust clang: error: linker command failed with exit code 1 (use -v to see invocation) I added this to my Podfile: pod 'Adjust', :git => 'git://', :tag => 'v4.2.5' I have installed pods successfully, but still get the above error....

Remove “heightForRowAtIndexPath” for iOS8

I'm trying to solve this problem for two days before finding the solution. Here it is. ====== Hi everyone, I actually manage the height of my tableViewCell in iOS7 with the delegate method heightForRowAtIndexPath: Now, in iOS8 I use the property tableView.rowHeight = UITableViewAutomaticDimension with autolayout and it works great...

View set as inputAccessoryView throws exception when added back into normal view

I have a text view, some decorations etc. in a view and I want that view to dock on keyboard, just like any other messaging app. When I'm about to display my text view, here is how I attach my view to the keyboard: -(BOOL)textViewShouldBeginEditing:(UITextView *)textView{ UIView *inputView = self.textInputView;...

canEvaluatePolicy Extra argument 'error' in call Swift Xcode 7

I work with Xcode 7 with swift and I would use the Touch Id. Only I have a error when I use canEvaluatePolicy. I understand my error, I call an argument too. Only if I do not call, it makes me a error because I did not manage my error...

Setting layer out of layer in UIbutton?

i want this type of button i have tried pictureBtn which is UIbutton ,i gave it a 5 pixel clear color corner radius and add a picture like camera below but last outer white line how to deal with this can anybody have ideas or something like control. ...

Swift: Set UIButton Image with CGRect

I'd like to set the image of a UIButton, but without creating all of the assets at different sizes. Since it should be just a grey rectangle, with some text on top, I'm trying to do this by creating a CGRect. The title is displayed as desired, and the button...

Switch between views using a Tabbar

I have an iOS application with a Tab Bar, and two subview. My first view is a Table View. So, I want to switch to the second view when I click on a cell of the first view, and keep the TabBar visible. When I do that using "Show" segue...

Cannot subscript a value of type [CLPlacemark] with an index type int

I would like to retrieve the current location. I work with on swift Xcode 7. I looked PLUSIEUR tutorials, but every time they use the same method. Here is my code and my error: ! Error : Cannot subscript a value of type [CLPlacemark] with an index type int import...

Blur Effect on TableViewCell when scroll

Right now I'm using LBBlurredImage to blur an image, but I want to change to iOS8's UIVisualEffectView to blur instead. I'm having a hard time implementing, any ideas? Implemented with LBBLurredImage: - (void)updateData { // Set up Screen self.screenHeight = [UIScreen mainScreen].bounds.size.height; //UIImage *background = [UIImage imageNamed:@"gray"]; UIImage *background =...

Swift - How to properly architect buttons in MVC?

I had wrote a block of code which made a UIButtons in a UIView with a segue action all in the ViewController file. The segue action allows the user to press on the a UIButton and pushes a new UIView with the title of that button on it. This worked...

Restrict app for iPhone devices lower than iPhone 5 with iOS 8 or 7 in AppStore

I planned to develop application with targeted devices iPhone 5/5S, iPhone 6/6+ . I don't want my application to be runnable on iPhone 4S. Can i able to achieve that? I googled some sites , they were mentioned that we can restrict older version mobiles like iPhone 3GS using front...

Custom UIButton Swift 2.0

I am trying to convert my project to Swift 2.0. I have a custom UIButton that is now causing an error when I try to build. My code is: var myButton = MyCustomButton.buttonWihType(.Custom) as UIButton This is working with my project in Swift 1.2 but now does not work. The...

Auto Rotation iOS 8 Navigation Controller

I have certain viewControllers which are managed by a UINavigationController (push and pop). I want to restrict different viewControllers to different orientations like the first one should be only in Portrait, second in portrait, third in landscape and fourth can be portrait and landscape both. I set a ViewController on...

Error after update to Swift 1.2

I updated shortly to Swift 1.2 which comes with Xcode 6.3.2 and wrote a few lines of code: let originView:UIView! override init() { super.init() } init(sourceView:UIView, menuItems:Array<String>){ super.init() originView = sourceView } This code runs perfect till I updated the new version of Xcode (6.3.2). Now I get the following...

iOS 8 simulators not visible in XCode 7 beta

I'm using the XCode 7 beta that Apple released during WWDC2015, and it looks like iOS8 simulators are not there in it. I tried downloading them using the Xcode > Preferences > Downloads > Components, but it doesn't list the simulators. I have Xcode 6.3.2 also on the mac, and...

UITableview with more than One Custom Cells with Swift

As absolute beginner I have to ask those questions: I want to use a UItableview with different custom TableviewCells. One Cell should have an image and a label. Another cell should have two label. A third cell should have a dayPicker. I don't have to create Tage cell in the...

Setting “AppleLanguages” doesn't change app language

I am trying to implement a function that can change app language. I tried to set it like this: let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject("de", forKey: "AppleLanguages") And after app restart language is still 'system default'. Now I test different languages by setting Scheme > Application Language > language. But is...

Will handling UIButton touch event inside a UITableViewCell subclass violate MVC?

There is a UITableViewCell subclass with a UIButton inside. A web call should be made when the button is pressed. The question is whether I should set the action in the controller, or can the action be set within the UITableViewCell subclass? Will the second option violate MVC pattern?...

UISearchController: show results even when search bar is empty

As I understand, the default behaviour of UISearchController is: On tapping search bar, background is dimmed and 'cancel' button is shown. SearchResultsController is not shown till this point. SearchResultsController is displayed only if search bar is not empty. I want to display SearchResultsController even when search bar is empty but...

Why is boundingRectWithSize wrong when using UIFont preferredFontForTextStyle?

I have found that a call to boundingRectWithSize is extremely incorrect, missing an entire additional line, when called with NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody]. However, using the font [UIFont fontWithName:@"Helvetica Neue" size:17.f], it is just fine. Here is test code showing the bug: - (void)viewDidLoad { [super viewDidLoad]; NSString *measureText =...

When creating new tableView entry the constraints don't work

I have a Master-Detail application that uses CoreData. Everything is hooked up fine and works as expected. There is just one problem with the display when adding a new entry. On the left is the Master's TableView with the entries and on the right is the Detail's View, where the...

How to add directions among two custom locations in Mapview for IOS 7 (objective c)

I have to add directions among two custom locations in IOS 7. Any one tell me please. Thanks. ...

UILabel text isn't updated when modal re-appears

I've created a reusable modal UIView as a singleton object, but am having trouble changing the text of a label it contains. When the modal appears a second time, the new text appears over the old text. I'm guessing this is due to the fact that the label is only... Framework Sort Date Next Birthday

Need to sort on iOS by date using but I need to order them based on the next birthday for a specific person. I tried to add the day and month with the current or next year and that helped but that will be a manual process, any recommendations...