Menu
  • HOME
  • TAGS

UITableViewCell Can Not Constrain Label to Right Edge

Tag: ios,swift,uitableview,autolayout,interface-builder

I have subclassed UITableViewCell (with a xib), and I have noticed that when I use autolayout/constraints, the labels that I place in Interface Builder do not show correctly at runtime.

First, I put three labels aligned left, center, and right with respect to the cell's content view.

When I run my app, The left-most label is on the left, the center label is on the right, and the right-most label is nowhere to be seen.

I logged the frame of the cell's content view at my -tableView:cellForRowAtIndexPath: (inside the UIViewController subclass that hosts the table view), and I get this value:

(0.0, 0.0, 600.0, 43.5)

The width is reported to be 600, but I assume this is the generic, 'any device' storyboard size (even though, weirdly, the cell comes from a separated xib with only the cell view, not a storyboard or the xib of a view controller), and it will be sized accordingly by the table view after being passed to it (AS a side note, notice the height being 43.5, not 44!).

I have tried several things, and found out the following:

  1. If I set constraints on my label against the leading (left), top and bottom edges of the cell, it displays appropriately.
  2. If I place the label at the right-most edge of the cell in Interface Builder, without any constraints, it shows where I placed it (but of course, on rotation to landscape, it will stay put a fixed distance from the left edge instead of sticking to the right edge).
  3. If I place the label anywhere, and add a constraint to the trailing (right) edge of the container, it is displayed or not depending on how much distance the constraint specifies. That is, the constraint seems to be stuck to the cell's original right edge of +600. If I place it near the left-most edge, but drag the constrain towards the trailing edge, it will appear somewhere on the right.

I tried logging the label's frame from within the cell's code, like this:

override func layoutSubviews()
{
    super.layoutSubviews()

    // (...label should be at the right position now?)

    println("Label frame: \(rightLabel.frame)") 
}

On Interface Builder, the label is 41 x 21 and is positioned at (271, 11). The log above is called twice for one row, and gives:

Label frame: (271.0, 11.0, 41.0, 21.0)
Label frame: (544.0, 11.0, 41.0, 21.0)

If, instead, I remove the trailing constraint and replace it by a leading constraint to the left edge of the content view, and leave the label on the same position in Interface Builder, the above logs give:

Label frame: (271.0, 11.0, 41.0, 21.0)
Label frame: (278.0, 11.0, 41.0, 21.0)

So, What is going on with trailing constraints on table view cells? How do I align a label to the right edge??

EDIT: I added the following line to the cell's layoutSubviews() method:

println("Own frame: \(self.frame)")

And I get this output:

Label frame: (271.0, 11.0, 41.0, 21.0)
Own frame: (0.0, 0.0, 600.0, 44.0)
Label frame: (544.0, 11.0, 41.0, 21.0)
Own frame: (0.0, 0.0, 600.0, 44.0)

So, the cell stays at 600 points wide, even after being put into the table view!

EDIT 2: So, I found the problem and obviously it was somewhere else: The table itself is stuck at 600 points wide, because I did not constrain it to the view controller's view edges in Interface Builder.

Silly me!

Once I pinned the table view's four edges to those of its parent view, the problem corrected itself.

First time using table views in Interface Builder...

Best How To :

First of all remove all constraint from that three label then follow this step and add constraint one by one as mentioned below.

  1. For Left Label select your label go to pin menu the add this 5 constraint for it.:

enter image description here

  1. For center label add this two constraint so it will always appear at center:

enter image description here

  1. For right label add this 5 constraint :

enter image description here

And the result will be for all screen:

enter image description here

HERE is the sample project.

Twilio Client Python not Working in IOS Browser

javascript,python,ios,flask,twilio

Twilio developer evangelist here. Twilio Client uses WebRTC and falls back to Flash in order to make web browsers into phones. Unfortunately Safari on iOS supports neither WebRTC nor Flash so Twilio Client cannot work within any browser on iOS. It is possible to build an iOS application to use...

try to recover views from custom cell

ios,uitableview

viewWithTag: is a very fragile way to get a reference to views, and isn't recommended. But what I think is happening is that you need to call viewWithTag: on cell.contentView rather than the cell itself. I'd recommend creating proper IBOutlets to hold your imageview and label....

How to draw each a vertex of a mesh as a circle

ios,unity3d,shader,mesh,particle

You can do it using geometry shaders to create billboarding geometry from each vertex on the GPU. You can then either create the circles as geometry, or create quads and use a circle texture to draw them (I recommend the later). But geometry shaders are not extensively supported yet, even...

UITapGestureRecognizer sender is the gesture, not the ui object

ios,xcode,swift,uigesturerecognizer

You can get a reference to the view the gesture is added to via its view property. In this case you are adding it to the button so the view property would return you you the button. let button = sender.view as? UIButton ...

Scaling everything up and down for different devices in UIStoryboard

ios,uistoryboard

You can do it by using Aspect Ratio property of AutoLayout. You can follow this tutorial. It gives a very nice explanation on how to scale everything up by using fix aspect ratio. http://simblestudios.com/blog/development/percentage-width-in-autolayout.html...

MFMessageComposeViewControllerDelegate not being called

ios,swift

It's crashing because your handler object is getting released and deallocated right after the call to handler.sendMessage(), and then a delegate callback is attempted on that now-deallocated object when you try to send or hit cancel. The object is getting released and deallocated because nothing is holding a strong reference...

What is the best practice add video background view?

ios,objective-c,swift,video

First of all, you have two main choices: use a imageView with a GIF or use a video for background with AVPlayer or MPMoviePlayerController. You can find a lot of example for both ways, here's a few: use a GIF for cool background video cover iOS In reply to your...

Call method after asynchronous request obj-c

ios,objective-c,asynchronous,uiviewcontroller,nsobject

You'll have to 'remember' which UIViewController calls the object. This can be done for instance with a property. in .h @property (nonatomic) UIViewController *viewController; in your .m file @synthesize viewController; Before calling the method, set the property with anObject.viewController = self; Then, you'll be able to call [viewController finishedPost:self]; inside...

App crashes when i start typing in uiseachbar in uitableview

ios

It seems that the Predicate is incorrect Try : NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.fullName contains[c] %@", searchText]; ...

IOS - Adjust cell height based on content

ios,uitableview,autolayout

If use AutoLayout the use this code You try to set the UITableView properties estimatedHeight. -(void)viewWillAppear:(BOOL)animated{ _messageField.delegate = self; _tableView.estimatedRowHeight = 65.0; _tableView.rowHeight = UITableViewAutomaticDimension; } Other wise use this UITableView Delegate Method - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 300; // your dynamic height... } ...

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

ios,swift,ios8,uiimagepickercontroller,ios8.3

Its orientation issues. UIImagePickerController wont support landscape mode.. Try this code source :: https://gist.github.com/mkeremkeskin/0ed9fc4a2c0e4942e451 - (BOOL)shouldAutorotate { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if ( orientation == UIDeviceOrientationPortrait | orientation == UIDeviceOrientationPortraitUpsideDown) { return YES; } return NO; } - (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown); } -...

How to get time difference based on GMT on Swift

ios,swift

I think your problem is that you are using a calendar with an unset time zone. Your calculation of adding 60*60*24*2 to the current time does not account for the two days when some timezones change to and from daylight savings time. Those days are 23 and 25 hours long....

looping variable in swift

swift,for-loop,uiimage

You don't need to create a new variable for each image, try this: for var i = 1; i < 8; i++ { images.append(UIImage(named: "image\(i)")) } This loop will create an array with 8 images without create the variables image1 to image8. I hope that help you!...

Getting video from Asset Catalog using On Demand ressources

ios,xcode,xcode7,ios9,asset-catalog

I think its not possible to use Asset Catalog for video stuff, Its simplify management of images. Apple Documentation Use asset catalogs to simplify management of images that are used by your app as part of its user interface. An asset catalog can include: Image sets: Used for most types...

Do I have to use both of these methods?

ios,swift,uitableview

No, you don't have to use both. Either you go with reloadCell technique or cell updates via beginUpdate and endUpdate. When you are reloading a particular row, internally table view system creates 2 cell and then blends in the new one with. You can remove the beginUpdates and endUpdates and...

Set color CFAttributedStringRef

ios,objective-c

Based on the comments on the question, you mentioned that the words will never change. You could potentially create a whole bunch of if/else statements checking every word selected against every word in an array. I have put this down as a more efficient alternative and it should hopefully work....

Parse and Swift Geopoints not saving

swift,parse.com,geopoints

That is because you are setting it but you are not saving the value you just set: if signUpError == nil { PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if error == nil { PFUser.currentUser()!.setValue(geoPoint, forKey: "location") PFUser.currentUser().saveInBackground() } } ...

How to create UITableViewCells with complex content in order to keep scrolling fluent

ios,swift,uitableview,cocoa-touch,ios-charts

What you're trying to do is going to inevitably bump into some serious performance issues in one case or another. Storing all cells (and their data into memory) will quickly use up your application's available memory. On the other hand dequeueing and reloading will produce lags on some devices as...

Build error after I localized Info.plist

ios,objective-c,xcode,swift,localization

Roll back those changes, add a InfoPlist.strings file to your project, localize it and then add the needed keys to it. For example: "CFBundleDisplayName" = "App display name"; "CFBundleName" = "App bundle name"; ...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

ios,objective-c,swift,uitextfield,uilabel

You can register your textField for value change event: [textField addTarget: self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged]; and in textFieldDidChange function update your label: - (void)textFieldDidChange { label.text = textField.text; } The function shouldChangeCharactersInRange is needed more for taking desisions whether to allow upcoming change or not...

How can I show ONLY the date (and not the time) using NSDateFormatter?

ios,iphone,swift

var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.locale = NSLocale(localeIdentifier: @"en_US") let d = NSDate() let s = dateFormatter.stringFromDate(d) ...

How can I fix crash when tap to select row after scrolling the tableview?

ios,xcode,swift,uitableview,tableviewcell

Because you are using reusable cells when you try to select a cell that is not in the screen anymore the app will crash as the cell is no long exist in memory, try this: if let lastCell = self.diceFaceTable.cellForRowAtIndexPath(lastIndexPath) as! TableViewCell{ lastCell.checkImg.image = UIImage(named: "uncheck") } //update the data...

Reference method from different class as curried function

swift,methods,currying

As methods in Swift are curried class functions, compiler has to decide which overload to choose. To reference instance's merge method you need to specify it's exact type: let instanceMerge: RACSignal -> RACSignal! -> RACSignal! = RACSignal.merge...

NSString to NSDate doesn't work

ios,objective-c,nsdateformatter

You have to set the date format as the string NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"]; NSDate *date = [dateFormatter dateFromString:myDate]; //Set New Date Format as you want [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSLog(@"%@",[dateFormatter stringFromDate:date]); ...

Omitting the return type in Swift closures

swift

I would not expect that example to have worked but it does In many cases, Swift can often infer types of variables and expressions. In this case, Swift looks at the value you're returning and can infer the type. If I modify that closure to specify a return type...

Difference between stringByAppendingString and appendString in ios

ios,objective-c,swift,nsstring,nsmutablestring

appendString: is from NSMutableString, stringByAppendingString: is from NSString. The first one mutates the existing NSMutableString. Adds to the end of the receiver the characters of a given string. The second one returns a new NSString which is a concatenation of the receiver and the parameter. Returns a new string made...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController

ios,swift,uitableview,uiviewcontroller

You just need to add this to your code in viewDidLoad. self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero]; EDIT: sorry i was written in objective -c here is in swift. self.tableView.tableFooterView = UIView(frame:CGRectZero) The tableview will display what appear to be extra blank rows to fill out the bounds if there are not...

Unexpectedly found nil while unwrapping an Optional value - Plist

ios,swift,plist

Seems to be no error in your code, Check that the arrays in plist has the same naming as in your code might be mistaken something with keys. You can check that by right-click on plist and Open-as then choose source code Like : objectForKey("name") called <key>name</key> objectForKey("image") called <key>image</key>...

animating a view on top of uitableview

ios,swift,autolayout

In initializeSettingsView() add nibView.setTranslatesAutoresizingMaskIntoConstraints(false). And then in viewDidload add the hight constraint to settingsView constraints.append(NSLayoutConstraint(item: settingsView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 90.0)) And you do not need to set the position of settingsView, since it will be layout at the right position based on...

What's the equivalent of finally in Swift

swift,try-catch-finally

If you are thinking about the SWIFT 2.0 error handling to be the same thing as exception you are missunderstanding. This is not exception, this is an error that conforms to a protocol called ErrorType. The purpose of the block is to intercept the error thrown by a throwing function...

Adding Image And title both to UIsegmentControl IOS

ios,uiimage,title,uisegmentedcontrol

The official documentation for -setImage:forSegmentAtIndex: says A segment can only have an image or a title; it can’t have both. There is no default image. So, no, there is no way to do what you want using the image and title properties. However, there are a few options to accomplish...

How to save text field value in uicollectionviewcell

swift,uitextfield,uicollectionviewcell

Implement in your ViewController the UITextFieldDelegate protocol, specifically the textField:didEndEditing method. Save your indexPath.row in the textField.tag as you're doing, and set the delegate to the controller, where you can save the value. This is a very simplistic example: class MyViewController : UITableViewController { var texts = [Int:String]() func tableView(tableView:...

How to add checkbox to uicollectionview in swift

swift,checkbox,uicollectionviewcell

Here is the example project available with checkbox cell. (objective - c) MyCell.m // A setter method for checked property - (void)setChecked:(BOOL)checked { // Save property value _checked = checked; // Update checkbox image if(checked) { self.checkBoxImageView.image = [UIImage imageNamed:@"Checked"]; } else { self.checkBoxImageView.image = [UIImage imageNamed:@"Unchecked"]; } } Your...

UITabBarViewController doesn't rotate - iOS

ios,uitabbarcontroller,auto-rotation,shouldstartload

Try to override this method, don't call super - (void)viewWillTransitionToSizeCGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { //[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; [self.selectedViewController viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; } ...

Is it possible to obtain an unique iCloud user ID on cocoa?

ios,iphone,cocoa,ipad,icloud

Yes, this is possible using CloudKit. You'll need a CKContainer, and you'll ask it to fetch the user record ID. That record ID is unique for your apps, but is also stable for that user this means the same iCloud account will have the same record ID, regardless of which...