Menu
  • HOME
  • TAGS

When creating new tableView entry the constraints don't work

Tag: uitableview,ios8,nslayoutconstraint

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 user enters in the new information.

I have a custom UITableViewCell to handle the formatting. The titleLabel of the new entry gets positioned by the constraints correctly. The detailTextLabel however does not seem to care about the constraints and just starts at the top left of the cell (so at the 0,0 position) and thus is on top of the titleLabel.

What am I doing wrong?

Here is the my custom initializer for the custom UITableViewCell:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    if (self) {

        self.backgroundColor = [UIColor darkGrayColor];
        self.textLabel.font = [Constants mainFontWithSize:16];
        self.detailTextLabel.font = [Constants mainFontWithSize:12];

        // correct default constraints
        self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.detailTextLabel.translatesAutoresizingMaskIntoConstraints = NO;

        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[textLabel]-35-|" options:0 metrics:nil views:@{ @"textLabel": self.textLabel }]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[detailTextLabel]-35-|" options:0 metrics:nil views:@{ @"detailTextLabel": self.detailTextLabel }]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-7-[textLabel(19)]-(3)-[detailTextLabel(14)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:@{ @"textLabel": self.textLabel, @"detailTextLabel": self.detailTextLabel }]];


    }
    return self;
}

Thanks

Best How To :

It looks like you're trying to add constraints to labels for a built-in cell style.

The reason why this doesn't won't work is because they're (public yet) internal labels, and Apple's code is optimized to remove its labels from their contentView when Apple believes the labels won't be needed.

When a label is removed from its superview, constraints are also removed. Later, when Apple adds the label to the superView, the constraints you had added affected the built-in behavior, so its label is now misplaced.

Either let Apple manage and layout its built-in cell styles on its own, or use a custom cell style with your own labels and constraints.

Bluemix authentication ios8 with google and facebook

facebook,authentication,ios8,bluemix,google-authentication

It is not currently supported to use the provided Facebook and Google authentication in the same application for Advanced Mobile Access. However using the Custom Authentication option you can write your own custom authentication logic inside of your application and Node.js application. Using this method the application could handle multiple...

TableViewCell overlaps text

ios,xcode,swift,uitableview,overlap

I can fix the problem. In the storyboard, the label have unchacked "Clears Graphics Context". I checked and for now it solved! Thanks for the help!

Add Storyboard UITableView and custom UITableViewCells to UIScrollView programmatically

uitableview,uiscrollview,storyboard

The answer is to relace: MealImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; with MealImageCell *cell = [_myTablView dequeueReusableCellWithIdentifier:CellIdentifier]; with _myTableView being the IBOutlet for the table view in Storyboard....

Why does didUpdateLocations: only have one location after locationManagerDidResumeLocationUpdates:

ios8,cllocationmanager

When you pause the location updates, the system considers that you don't need the location for now. Resuming it will only give you the current location. This is a normal behavior.

Swipe up to show button in UITableView?

ios,swift,uitableview,ios8,uicollectionview

Put the button on your first row and the rest of the data after. Set an inset on the tableview so the first row is hidden until the user scrolls.

UITableView(grouped) adds extra empty header at the bottom

ios,objective-c,uitableview

Instead of returning a CGRectZero view for the footer, simply return nil. - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { return nil; } Also you do not seem to have implemented heightForFooterInSection:section. That should return 0.0. This seems to have come up before and it would seem iOS often pads the bottom...

UITableView reloadData not working when button tapped

ios,objective-c,uitableview

Are you properly assigning your agendaTable you created to your 'agendaTable' property in your viewDidLoad? self.agendaTable = agendaTable; ...

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

After an insert into the UITableView : custom the cell

ios,objective-c,uitableview

You need to use UITextField instead of UILabel. When you insert a new cell, set this UITextField's enabled property to true. When loading all the other cells remember to set it to false to disable editing (the same cell maybe used at more than one place)....

How to get tableview cell text label from 2nd viewcontroller to a label from 1st viewcontroller?

ios,uitableview,delegates,nsnotifications

1st In VC2, you must create delegate @protocol VC2Delegate; @interface VC2 : UIViewController @property (nonatomic, weak) id <VC2Delegate> delegate; @end @protocol VC2Delegate <NSObject> @required - (void)changeToText:(NSString *)text; @end @implementation VC2 // this is your "完了" action - (IBAction)doneAction:(id)sender { ... [self.delegate changeToText:@"what you want"]; } @end 2nd, add the delegate...

NSFetchRequest to retrieve Every Student's Maximum Test Score for Every Subject in CoreData Entity

ios,uitableview,core-data,nspredicate

Okay, here is what I came up with. Hope this helps others out: I parsed the Managed Objects into NSMutableArrays based upon the "class" (race in my case). Then I used put each NSM Array into a NSMutableDictionary where an index acted as the key. This dictionary and the arrays...

How to i create new arrays using swift?

ios,arrays,swift,ios8

Because your shopping lists are arrays of strings, and you want to put these arrays into a new array of shopping lists, you need an array of arrays of strings. Like this: let contentsOfShoppingList1 = ["Bananas", "Apples", "Oranges"] let contentsOfShoppingList2 = ["Eggs", "Bread", "Salt"] var shoppingListsArray = [[String]]() shoppingListsArray.append(contentsOfShoppingList1) shoppingListsArray.append(contentsOfShoppingList2)...

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

Error after update to Swift 1.2

ios,xcode,swift,ios8,xcode6.3.2

Change your this line : let originView:UIView! to var originView:UIView! And you are done....

Reusing a UITableViewCell's IBOutlets with two different UITableViewControllers

swift,uitableview,code-reuse,iboutlet,tableviewcell

This issue arises while registering the UITableViewCell class as tableView.registerClass(SwitchCell.self,forCellReuseIdentifier:"SwitchCell2") Remove that line tableView.registerClass(SwitchCell.self,forCellReuseIdentifier:"SwitchCell2") and set the cellIdentifier in storyboard..it works...

Fatal error when unwrapping CLLocation Location Coordinate

ios,iphone,swift,ios8,optional

It looks like you aren't giving the CLLocationManager enough time to update the location. I looked at the documentation, and in the statement locationManager.location.coordinate.latitude, location is the only one that's an optional. It's implicitly unwrapped, so that's why you don't need an ! after it. In the printCurrentCoordinates method, you...

UITableView moveRowAtIndexPath displays duplicate cells

ios,uitableview

The cause of the problem was a bug in the re-ordering of my data provider. I moved a cell in the tableview but the data array did not reflect that change.

When adding a UITableView to an existing ViewController with a JTCalendar view up top, the table covers the entire view

ios,objective-c,uitableview

You're initializing the tableview with a fullscreen frame, and haven't told it to shrink down to the height you want. Try applying a fixed height constraint with the height you want, then add constraints to the left, right, and bottom sides of the tableview. Apple has lots of documentation on...

Save UITableViewCell Checkmark Selection in Swift

swift,uitableview

Yep, you answered your own question here. You need to store lastSelectedIndexPath some how (ie to whatever you're using for persistence). A simple way (read: not the best way) to do this if you don't have any sort of database set up already is to store it using NSUserDefaults.

Move UIToolbar with keyboard iOS8

xcode,ios8,uitoolbar

First: self.view do not have the toolbar, you have to move your toolbar separately.. Second: self.navigationController.toolbar = CGRectMake.. this is wrong, self.navigationController.toolbar.frame = CGRectMake.. is the correct way. Third: Using self.navigationController.toolbar.frame.origin.y - keyboardFrame.size.height +self.navigationController.toolbar.frame.size.height i think you have to correctly calculate the frame of the self.navigationController.toolbar based from the height...

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

ios,swift,ios8

First, assuming that authenticationObject is an LAContext, you can't call its canEvaluatePolicy method without handling the error that it potentially throws. Making sure that errors get handled* is what throws methods are all about. Second, when ObjC APIs that return BOOL with an NSError out-parameter are imported into Swift, they...

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

Updating Core Data Model using two separate View Controllers

ios,objective-c,uitableview,core-data

I resolved this. Here is what was done. First off there was serious cleanup of files, arrangement, etc. There were some objects, attributes, etc., that didnt make sense. Renaming things helped a lot as I was causing a lot of confusion. There was a one-to-one relationship between my List and...

How to change element title inside UITableViewCell?

ios,objective-c,iphone,swift,uitableview

If your function is playPost(), you could change the value passed in (which is the sender of the function, by default) like this: func playPost(sender: UIButton) { sender.setTitle("New title", forState: UIControlState.Normal); } ...

canEvaluatePolicy Extra argument 'error' in call Swift Xcode 7

ios,xcode,ios8,xcode7

As mentioned in Using Swift with Cocoa and Objective-C, all Objective-C methods that use NSError to return an error object will now throw when called from Swift 2.0, so you need to use: do { try method() } catch let error as NSError { reportError(error) } Removing the reference to...

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

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

iphone,swift,ios8,popup,xcode6

It sounds like you want a UIAlertController, check this out: @IBAction func popUpButton(sender: UIButton) { //This is where you declare and initialize your `UIAlertController` let alertController = UIAlertController(title: "Alert", message: "Test Alert", preferredStyle: .Alert) //You give the `UIAlertController` an action, which basically has a cancel button, that just cancels out...

UITableViewCell Can Not Constrain Label to Right Edge

ios,swift,uitableview,autolayout,interface-builder

First of all remove all constraint from that three label then follow this step and add constraint one by one as mentioned below. For Left Label select your label go to pin menu the add this 5 constraint for it.: For center label add this two constraint so it will...

Using the device simulator for iOS 8 with Xcode 7

ios8,xcode7,ios9

Xcode release note says below thing, Simulator Xcode 7.0 beta does not support iOS 8.4 and earlier simulator runtimes. (20699475) Refer this link for more info....

Why is boundingRectWithSize wrong when using UIFont preferredFontForTextStyle?

ios8,nsstring,uilabel,uifont

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: Here's the code I used. In the view controller:...

Resize a UITableView

swift,uitableview,resize,frame

My first guess was that you were using AutoLayout. Changes to view frames often don't have any effect in that case. Have you double-checked to make sure it's turned off for you storyboard? Failing that, the most likely cause of changing having no effect is broken outlets. Add a println...

Switch between views using a Tabbar

ios,xcode,swift,ios8

I've fix my problem. I've originally put the line of code bellow on the viewDidLoad() of my controller : tabBarController.selectedViewController = mySecondViewController After moving this line in a different methode, call by a simple button, that worked......

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

UISwipeGestureRecognizerDirection only Recognizes Right Gesture

ios,objective-c,uitableview,uiswipegesturerecognizer

Use this code... I hope you don't mind its in swift. override func viewDidLoad() { super.viewDidLoad() var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeRight.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(swipeRight) var swipeDown = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeDown.direction = UISwipeGestureRecognizerDirection.Down self.view.addGestureRecognizer(swipeDown) } func respondToSwipeGesture(gesture:...

UITableViewCell conflicting height constraint

ios,swift,uitableview,autolayout

For reasons unbeknownst to be, setting the priority of the constraints down to 999 seems to resolve this issue for autosizing UITableViewCells.

UITableView Using two arrays

ios,swift,uitableview

Try this func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellID = "cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.text = category.books[indexPath.row] cell.backgroundColor = colorArray[indexPath.row % 5] return cell } ...

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

Swiftyjson bundled file

ios,json,swift,uitableview,swifty-json

Ok: Read out your file let path = NSBundle.mainBundle().pathForResource("filename", ofType: "json") let jsonData = NSData(contentsOfFile: path!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil) load data to SwiftyJSON let json = JSON(data: jsonData) Get the Object you want: let name = json["key1"]["key2"].stringValue // get any value Or cast as Array if let array =...

How can I sort an array from Core Data using a stored integer attribute?

ios,arrays,swift,uitableview,core-data

First, your array with a fetch requests necessary to retrieve the objects is not very efficient. Just use a NSFetchedResultsController and the index paths will automatically point to your objects. In addition, you get great memory and performance optimizations for free. As has been pointed out in the comments, you...

UITableView Sections. For each cell - a section with the title

ios,uitableview

You have to return like this for numberOfSectionsInTableView method instead of 1. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return sectionsTitle.count; } And in cellRowAtIndexPath: method - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *simpleTableIdentifier = @"TableCell"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc]...

Why doesn't a UITableView scroll until I have 2 additional rows?

ios,uitableview

UIScrollView (from which UITableView inherits) has a alwaysBounceVertical property. If you set this to true, either in code or Storyboard, the table view will be vertically 'scrollable' regardless of how many rows it has.

some text of my cells changes color when I scroll my tableview

ios,uitableview,colors,cell,changes

You need an else in the code you quoted. What colour do you want it to be when the dateIsGreaterThanDate test is false?

Autolayout works great on iOS 8, crashes on iOS 7

ios,ios7,ios8,autolayout

Turns out these two lines caused the crash: self.ninjaStarImage.layer.removeFromSuperlayer() self.view.layer.addSublayer(self.ninjaStarImage.layer) Moving them to viewDidLayoutSubviews solved the problem...

Multiple NSURLSessions Causing UITableView Problems

ios,objective-c,uitableview,nsurlsession

Besides assuming that your network requests aren't erroring (you should at least log if there are network errors), there are threading issues. Your NSURLSession callback probably runs on a background thread. This makes it unsafe to call UIKit (aka - [_tableView reloadData]). UIKit isn't thread safe. This means invoking any...

iOS Swift Problems putting 2 or more UITableView in a UIScrollView with datasource and delegate

ios,swift,uitableview,uiscrollview

First of all, you should probably store a reference to the second tableView somewhere and not just put it into your scrollview. But this is not the reason for your crash. Secondly:, the reason for your crash. You don't store a reference to 'foo', which means it will be deallocated...

UITableCell not resizing properly

ios,swift,uitableview

Try to use layoutIfNeeded for update constraint immediately. For fix warning, you should set one of your vertical constraint priority to 999. All works properly if set Accessory view to None...

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

Auto Rotation iOS 8 Navigation Controller

objective-c,iphone,ios8,uinavigationcontroller,autorotate

Just subclass UINavigationController and override appropriate methods: .h File: @interface CustomUINavigationController : UINavigationController @property BOOL canRotate; @end .m File: @implementation CustomUINavigationController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any...

How can I tell which custom UITableViewCell's UIButton has been tapped?

ios,objective-c,uitableview

Declare a protocol on the cell, which the tableview controller will conform to, then you can call a method on button click and can even send "self" as a parameter to get the actual cell.