ios8,nsstring,uilabel,uifont , Why is boundingRectWithSize wrong when using UIFont preferredFontForTextStyle?

Why is boundingRectWithSize wrong when using UIFont preferredFontForTextStyle?


Tag: ios8,nsstring,uilabel,uifont

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 = @"I'm the king of Portmanteaus ... My students slow clap";

    CGSize maxSize = CGSizeMake(226.f, CGFLOAT_MAX);

    UIFont *targetFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];

    CGRect stringRect = [measureText boundingRectWithSize:maxSize
                                                         options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                                      attributes:@{ NSFontAttributeName : targetFont }

    UILabel *drawLabel = [[UILabel alloc] initWithFrame:stringRect];
    drawLabel.font = targetFont;
    [self.view addSubview:drawLabel];
    drawLabel.textColor = [UIColor blackColor];
    drawLabel.text = measureText;
    drawLabel.numberOfLines = 0;

And the output:

enter image description here

However, if I make targetFont = [UIFont fontWithName:@"Helvetica Neue" size:17.f];

It renders properly:

enter image description here

In the first case, the size is {226.20200000000008, 42.281000000000006}, but in the correct second case the size is {228.64999999999998, 60.366999999999997}. Therefore, this is not a rounding issue; this is missing an entire new line.

Is it wrong to pass [UIFont preferredFontForTextStyle:UIFontTextStyleBody] as an argument into boundingRectWithSize?


Per the comments in the answer below, I believe there is a bug with how iOS treats three periods in connection with the proceeding word. I have added this code:

measureText = [measureText stringByReplacingOccurrencesOfString:@" ..." withString:@"…"];

and it works properly.


A label adds a little margin round the outside of the text, and you have not allowed for that.

If, instead, you use a custom UIView exactly the size of the string rect, you will see that the text fits perfectly:

enter image description here

Here's the code I used. In the view controller:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *measureText = @"I'm the king of Portmanteaus ... My students slow clap";
    CGSize maxSize = CGSizeMake(226.f, CGFLOAT_MAX);
    UIFont *targetFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
    CGRect stringRect = [measureText boundingRectWithSize:maxSize
                                                  options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                               attributes:@{ NSFontAttributeName : targetFont }
    stringRect.origin = CGPointMake(100,100);
    StringDrawer* sd = [[StringDrawer alloc] initWithFrame:stringRect];
    [self.view addSubview:sd];
    [sd draw:[[NSAttributedString alloc] initWithString:measureText attributes:@{ NSFontAttributeName : targetFont }]];

And here is String Drawer (a UIView subclass):

@interface StringDrawer()
@property (nonatomic, copy) NSAttributedString* text;

@implementation StringDrawer

- (instancetype) initWithFrame: (CGRect) frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor yellowColor];
    return self;

- (void) draw: (NSAttributedString*) text {
    self.text = text;
    [self setNeedsDisplay];

- (void)drawRect:(CGRect)rect {
    [self.text drawInRect:rect];


Also, if your purpose is to make a label that contains the text by sizing its height, why not let Auto Layout do its thing? This next screen shot is a UILabel, with a width constraint 226, and no height constraint. I've assigned it your font and your text, in code. As you can see, it has sized itself to accommodate all the text:

enter image description here

That was achieved by this code, and no more was needed:

NSString *measureText = @"I'm the king of Portmanteaus ... My students slow clap";    
UIFont *targetFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
self.lab.font = targetFont;
self.lab.text = measureText;


UI Local Notification - Background Reschedule

I'm learning to develop application for ios with swift, and I'm one doubts, already googled and i not found. I'm creating a to-do list app, and was wondering if there is a way to reschedule a notification when it appears to the user For example the user registers a task...

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...

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...

What does @“//” do in childWithName and when to use it

I'm working on a SpriteKit project and my SKSpriteNode has a simple name: = @"cat" However, when I try to do [self childWithName:@"cat"], I do not retrieve my object. Through some research I noticed some people mentioning I should be doing [self childWithName:@"//cat"] and that works. I was wondering...

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...

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...

Difference between stringByAppendingString and appendString in ios

What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

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...

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...

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... 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...

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...

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,...

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...

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:...

NSURL URLWithString is shortening very long strings with an ellipsis “…”, creating invalid NSURL objects

I am trying to use NSURL URLWithString to create an NSURL object from a potentially very long file path with a very long file name. When I convert the file path to an NSURL object using URLWithString, the path gets shortened and an ellipsis " ... " is put in...

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...

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...

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...

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...

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....

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...

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...

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 =...

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...

Swift - Issue trying to access to Singleton object

This is my first question on StackOverflow, I'll try to be specific. I am trying to implement the Singleton pattern on my app, without success so far. When I try to access to my Singleton, it seems that the program is not accessing the real singleton, but a copy of...

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...

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...

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...

SWIFT : Convert String from XLM to NSDate

The following code works on the simulator but doesn't on devices. I tried to replace Z with xx with no luck. Any help appreciated. Thanks. func convertDateStringToNSDate(dateString: String) -> NSDate { var dateFormatter = NSDateFormatter() // Sat, 20 Jun 2015 16:50:20 +0200 dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss xx"...

Converting string to date with NSDateFormatter

Im trying to convert this string '2015-05-08T09:44:25.343' format to date 'dd/MM/YYYY' format What I`m doing wrong? my date comes Nil. // convert 2015-05-08T09:44:25.343 to dd/MM/yyyy NSString *str = @"2015-05-08T09:44:25.343"; NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init]; [dateFormat setDateFormat:@"dd/MM/yyyy"]; NSDate *date = [dateFormat dateFromString:str]; NSLog(@"%@",date); NSString *convertedString = [dateFormat stringFromDate:date]; NSLog(@"%@", convertedString); ...

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. ...

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...

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...

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;...

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...

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...

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...

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...

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 =...

NSDictionary and string literal keys

Does using a string literal like @"key" in setObject(id):forKey(id) only work because the compiler optimizes all instances of the string literal to point to the same object? Or does retrieving an object with objectForKey(id) actually compare the string value of the key? What if the NSDictionary was created by an...

Creating a “generated” number from an NSString

I'm trying to find a way that I can turn any string into a generated, deterministic number. That is... Each time that the same string is used it will create the same number. Different strings will (probably) create different numbers. For instance, you could add the letter indices in the...

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...

Shuffle NSArray

I got an NSMutableArray with a rather small number of objects that varies from 1 to max 20. When user taps a button I want to select one random object and display it. I've tried shuffling the array: srandom(time(NULL)); for (NSInteger x = 0; x < [array count]; x++) {...

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...

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...

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:...

Opening and closing form animation

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