jeudi 25 juin 2015

How to add button to UITableViewController in static cells?

I have a UITableViewController,and have set its content to Static Cells,style to grouped. My question is how to add the red button to the tableview appropriately,Any ideas?

enter image description here

See more ..

custom table cell displaying nil

I'm trying to set the title and display a button in my custom cell object in my second table view controller, but only my first dynamic prototype cell is displaying text.

The first prototype cell is UITableViewCell and the second is the custom object. In my first view controller I implement almost the same exact method and it works completely fine. Not sure where my error could be, the models I use have all their data in them. I have the correct cell identifier in my storyboard, and the connection from custom cell to the UIButton is set.

Thanks in advance.

Method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CellIdentifier";
    static NSString *QuestionSectionIdentifier = @"QuestionSectionCell";


    if (indexPath.section == 0) {
        UITableViewCell *cellQuestion = [tableView dequeueReusableCellWithIdentifier:QuestionSectionIdentifier];
        if (cellQuestion == nil) {
            cellQuestion = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:QuestionSectionIdentifier];
        }
        if (indexPath.row == 0) {
            cellQuestion.textLabel.text = _headerQuestion.question;
            NSLog(@"question here %@", cellQuestion.textLabel.text);
        }

        return cellQuestion;
    }

    else {
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
        if (indexPath.section == 1) {


            if (indexPath.row == 0) {
                [cell.firstButton setTitle:_headerQuestion.questionAuthor.fullName forState:UIControlStateNormal];
                [cell.firstButton setTag:_headerQuestion.questionAuthor.userID];
                [cell.answerLabelField setHidden:YES];

                NSLog(@"section 1  %@", cell.firstButton.titleLabel.text);

            }


        }

        else  if (indexPath.section == 2) {
                Answer* answer_num =  [_headerQuestion.answers objectAtIndex:indexPath.row]; //object at index
                [cell.firstButton setTitle:answer_num.answerAuthor.fullName forState:UIControlStateNormal];
                [cell.firstButton setTag:answer_num.answerAuthor.userID];
                cell.answerLabelField.text = answer_num.answer;

        }
        return cell;
    }

}

See more ..

UITableViewCell subclass IBOutlets returns nil

I've set up an UITableViewCell subclass from storyboard and connected the subviews as IBOutlets, as you can check here:

public class WaitingStatusTableViewCell: UITableViewCell {

@IBOutlet weak var leftBoxView: UIView!
@IBOutlet weak var leftTimeLabel: UILabel!
@IBOutlet weak var leftTitleLabel: UILabel!

Overrided the initialisers:

 override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.initialConfigure()
}

required public init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.initialConfigure()
}

And on the initialConfigure function I try to configure some properties of my subviews

    func initialConfigure() {
    self.leftBoxView.backgroundColor = UIColor.clearColor()
    self.leftBoxView.layer.shadowColor = UIColor.darkGrayColor().CGColor
    self.leftBoxView.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 12.0).CGPath
    self.leftBoxView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
    self.leftBoxView.layer.shadowOpacity = 1.0
    self.leftBoxView.layer.shadowRadius = 2
    self.leftBoxView.layer.masksToBounds = true
    self.leftBoxView.clipsToBounds = false
}

It doesn't work at all, I receive the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Any ideas?

Oh, by the way, it works on drawsRect function, but I really want to understand the "why"

See more ..

Predicates and combined filters in core data?

I'm not using Core Data currently, but I'm about to switch to it from Realm, if I'm sure a certain thing will work, which is vital to the way my application currently works. I have a model with two objects:

Message:
date - NSDate
text - String
images - One-to-many > Image

Image:
imageURL - String
message - Many-to-one > Image

I have a table view which displays both Images and Messages. I need to know what should go at a certain index path, for when UITableView wants to know. So I need to be able to perform a query akin to:

"Give me an ordered list of images and messages, messages sorted by their date and images sorted by their message.date".

How could I do this?

See more ..

Why UIRefreshControl jumping?

I try to use the UIRefreshControl with swift 1.2 and works fine except the UI. It is jumping and I dont know why. Here is what I am doing:

class ViewController: UIViewController {

     var refreshControl:UIRefreshControl!

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.refreshControl = UIRefreshControl()
        self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
        self.tableView.addSubview(refreshControl)
    }

    func refresh(sender:AnyObject) {
        // Code to refresh table view
    }

}

And you can download my poc project from here: POC project

While you pull down the tableView, suddenly jump a little bit down. Has anybody any idea why?

If I use with UITableViewController, It works fine but I dont want to use this UI object. I would like to use a simple UITableView in a UIViewController.

See more ..

Position a view with myView.frame

I have done a simple code:

myView.frame = CGRectMake(0, 0, 150, 150) 

in viewDidLoad and it is working well as expected.

But after I link this view from a table view and embed it into a navigation controller, it doesn't work.

Did I miss something?

See more ..

Cell reuse beginner? Tapping button in one cell affects another

I have a TableViewController with a custom cell. When I tap the like button inside one of the cells, it is causing at least one other cell to have the like button tapped.

I am using Parse, and it is not affecting the actual like count of the second one which is being ghost tapped, but it is disabling the like button and turning it red.

I have read about cell reuse, and similar topics but am completely lost. I am new to swift, and if someone could help me navigate how to fix this, I can't find a solution on SO about Swift, and Parse.

TableViewController

 @IBAction func likeButtonTapped(sender: AnyObject) {

    let chinTwo = self.timelineData[sender.tag] as! PFObject

    chinTwo["likeCount"] = (chinTwo["likeCount"] as! Int) + 1

    sender.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)

    chinTwo.saveInBackgroundWithBlock {
        (success: Bool, error: NSError?) -> Void in
        if (success) {
            println("Worked")
        } else {
            println("Didn't Work")
        }
    }

    self.tableView.reloadData()

}

TableViewCell

@IBAction func likeTapped(sender: AnyObject) { 
    likeButton.enabled = false
}

The same problem occurs with the report button.

See more ..

How to find TableView section header indexpath?

I want to do some action according to TableView section header indexpath, is there any method to trace section header Indexpath?

See more ..

Passing Data between two UITableViews

How I can pass datas between two UITableViews? One TableView should have multiple defined rows with check marks (like a setup panel). This checked rows in TableView one should then be visible in the second TableView. Any idea or code example to do this? Thanks.

See more ..

How to Pass Data From UICollectionViewCell to UITableViewCell

I want to pass data from UICollectionViewCell when I selected to UITableView and displayed inside UITableView Inside the array

This is a images are for reference :

enter image description here

enter image description here

so I output the data to string

cell.foodName.text = foodnameout
cell.priceS.text = foodpriceout
cell.foodcounttext.text = foodcountout

println("\(cell.foodName.text):\(cell.foodcounttext.text)")

See more ..

TableView Header hight according to screen size

I have a TablevView with a TableView header created by the interface builder inside the same xib of the TableView.

I want to set the height of the header according to the screen size for example I want the header to take 50% of the screen size.

Here is what I get now with the static height in the iPhone 4s.

Tableview header in iPhone 4s

And here is is what I get in the iPhone 6.

Tableview header in iPhone 6

Note that the content of the header is static, so I am no looking for the dynamic height cell.

I cant set constraints to the header using auto-layout ! I tried to set a height constraint based of the height of the TableView, but I can't reach that in interface builder.

See more ..

Delete Row from Table view

I am developing an IOS app.delete the row in table view and data load in core data in table view.When Click the delete button App crash. Reason is reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (18) must be equal to the number of rows contained in that section before the update (18), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'.. _fetchedobj is an NSArray to Fetch data from core data

//Code is
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _fetchedobj.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyReuseIdentifier";
    UITableViewCell *cell = [myTable dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier];
    }
   data = [_fetchedobj objectAtIndex:indexPath.row];
    return cell;
    }


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [tableView beginUpdates];
            NSManagedObject *managedObject = [_fetchedobj objectAtIndex:indexPath.row];
            [self.managedObjectContext deleteObject:managedObject];
            [myTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [myTable endUpdates];
        }
    }

See more ..

How to get click event UIbutton on tableView cell?

I have taken UIbutton on TableViewCell, but when I click on a row, only the row get clicked, but I want to click only the button on that row.

How is this possible?

See more ..

Error: 'NSInvalidArgumentException' ... unrecognized selector sent to instance

Here is my problem, I'm trying to make a clone of Snapchat, a very simple one, using Parse.com with the default project given in the page, everything was going ok, until I have to take pictures and save them to send them to an user. With this code:

import UIKit
import Parse

class UsersTableViewController: UITableViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {


    var usersArray: [String] = []

    var activeRecipient: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        var query = PFUser.query()
        query?.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)

        var users = query?.findObjects()

        if let user = users {
            for username in user {
                println(username.username!!)

                usersArray.append(username.username!!)


            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return usersArray.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("snapCell", forIndexPath: indexPath) as! UITableViewCell

        cell.textLabel?.text = usersArray[indexPath.row]

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        activeRecipient = indexPath.row

        pickImage()


    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {

        //Upload image to parse //error come somewhere from here I think


        println("Image Selected")
        self.dismissViewControllerAnimated(true, completion: nil)


        var imageToSend = PFObject(className:"Image")
        imageToSend["image"] = UIImageJPEGRepresentation(image, 0.5)
        imageToSend["senderUsername"] = PFUser.currentUser()!.username
        imageToSend["recipientUsername"] = usersArray[activeRecipient]

        imageToSend.save()

    }

    func pickImage() {

        var image = UIImagePickerController()
        image.delegate = self
        image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        image.allowsEditing = false

        self.presentViewController(image, animated: true, completion: nil)

    }


}

The error:

2015-06-24 15:03:13.414 SnapClomSwift[2043:124661] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableData PF_base64EncodedString]: unrecognized selector sent to instance 0x7a648960'

Is not very helpful to debug, any help??

EDIT1: I would think the parse function is the last calling and breaking everything but I'm not sure.

screenshot of the exception

EDIT2: I have I guess fixed but I'm not sure what was in the first place, still. The new code is this:

var imageToSend = PFObject(className:"Image")
        //var imageData = UIImagePNGRepresentation(image)
        imageToSend["senderUsername"] = PFUser.currentUser()!.username!
        imageToSend["recipientUsername"] = usersArray[activeUser]
        imageToSend.saveInBackgroundWithBlock({
            (success: Bool, error: NSError?) -> Void in
            if (success == false) {
                // Error.
                println("Error horray! \(error?.description)")
            } else {
                // There was a problem, check error.description

                let imageData = UIImagePNGRepresentation(image)

                let imageFile = PFFile(name: "image-png", data: imageData)

                imageToSend["image"] = imageFile

                imageToSend.saveInBackgroundWithBlock({
                    (success: Bool, error: NSError?) -> Void in

                    if success == false {

                        println("something is fucked up \(error?.description)")
                    } else {

                        println("Cool")
                    }
                })

                println("Done")
            }
        })

I guess this is not a solution but a workaround so I'm going to accept Zaph's answer.

See more ..

UITableViewCell shadow disappears after scroll

I have subclassed UITableViewCell class to add shadow below my cell. The shadow is added correctly, when TableView appears on screen. But, when I scroll tableview down, and cell with shadow hides above the screen, the shadow disappears.

- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.shouldAddShadow) {
        self.layer.shadowOpacity = 0.5;
        self.layer.shadowRadius = 1.5;
        self.layer.shadowOffset = CGSizeMake(0, 3);
        self.layer.shadowColor = [[[UIColor appDarkDividerColor] colorWithAlphaComponent:0.9] CGColor];
        [self setClipsToBounds:NO];
        [self.layer setMasksToBounds:NO];
        CGRect shadowFrame = self.layer.bounds;
        CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:shadowFrame].CGPath;
        self.layer.shadowPath = shadowPath;
    }
}

See more ..

Access UITextField's text content (swift)

I'm trying to access the content of UITextFields that's nested in a UITableView when a "save" button is pressed. However, debugging (as shown further below) shows that I can access anything about the texfield except its text.....Whatever I type inside it before pressing the button has no impact... I Feel like I should use the UITextField Delegate but don't understand neither why nor how... Can anyone help ?

This is the code i'm using (in Swift)

@IBAction func saveNewGuestButton(sender: UIBarButtonItem) {
    let entity : NSEntityDescription = NSEntityDescription.entityForName("Guest", inManagedObjectContext: self.managedObjectContext)!
    // Initialize Record
    let record : Guest = Guest(entity:entity, insertIntoManagedObjectContext:managedObjectContext)
    // Populate Record
    for i in 0..<3
    {
        let indexPath : NSIndexPath = NSIndexPath(forRow: i, inSection: 0)
        let cell = tableView(self.tableView, cellForRowAtIndexPath: indexPath) as! newGuestProtoCell
        if i==0
        {
            record.guestFirst = cell.newGuestFirstNameTextField.text
            println("indexPath :\(indexPath), recorded : \(record.guestFirst) and TextField : \(cell.newGuestFirstNameTextField.text) + \(cell.newGuestFirstNameTextField). test : \(cell.newGuestFirstNameTextField.defaultTextAttributes) and \(cell.newGuestFirstNameTextField.attributedText) and \(cell.newGuestFirstNameTextField.placeholder) and \(cell.newGuestFirstNameTextField.tag)")
        }
        if i==1
        {
            record.guestLast = cell.newGuestLastNameTextField.text

            println("indexPath :\(indexPath), recorded Last : \(record.guestLast), recorded first : \(record.guestFirst) and textfield : \(cell.newGuestLastNameTextField.text)")
            //newGuest["lastName"] = cell.newGuestLastNameTextField.text
        }
        if i==2 && guestImage != nil
        {

            record.guestImage = UIImagePNGRepresentation(guestImage) as NSData
            println("indexPath :\(indexPath), recorded image: \(record.guestImage.superclass) and UIImageView's image : \(cell.guestImageIV.image)")
        }
    }

The console prints the following, which proves that the problems is not in my tableview, my "for" loop to access it nor the textfield itself (or it's "outlet") :

indexPath : {length = 2, path = 0 - 0}, recorded : and TextField : + >. test : [NSParagraphStyle: Alignment 0, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 4, Tabs ( 28L, 56L, 84L, 112L, 140L, 168L, 196L, 224L, 252L, 280L, 308L, 336L ), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection -1, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0, NSShadow: NSShadow {0, -1} color = {(null)}, NSFont: font-family: ".HelveticaNeueInterface-Regular"; font-weight: normal; font-style: normal; font-size: 14.00pt, NSColor: UIDeviceRGBColorSpace 0 0 0 1] and Optional() and Optional("First Name") and 0 indexPath : {length = 2, path = 0 - 1}, recorded Last : , recorded first : and textfield : indexPath : {length = 2, path = 0 - 2}, recorded image: Optional(NSMutableData) and UIImageView's image : Optional( size {1500, 1001} orientation 0 scale 1.000000)

See more ..

NSMutableArray move last object to first position

I have a UITableview that has 8 rows corresponding to my NSMutableArray with 8 elements.

I want to move index 7 in the array to index 0, pushing down the previous index 0 to index 1. The previous index 6 would now be in index 7 position.

When I use - insertObject:atIndex: my tableView crashes saying that the number or array items is now 9 instead of 8.

I have tried to create a temp array to hold the elements of the mutable array but I want a smooth transition of the cells moving downward instead of just reloading. Is there any way to do this?

See more ..

ios 8.3 heightforrowatindex path is not calling when view is popped back from nextview in device but working in simulator

In xcode6.3 we are using uitableview in a view and calling heightforrowatindexpath which hides rows on selection

here is situation to hide rows if we go to next view and select a category from first section it has to reveal two hidden rows

and when we select otherthan first section in next view

it has hide those two revealed rows

in simulator after coming back from nextview controller it is calling heightforrowatindexpath method but in real device it is not calling

problem is in iOS 8.2 it is working good and in iOS 8.3 simulator also it is working good but in ios8.3 and in ios 7 it is not working

See more ..

after adding uitableview to uiview didselectrowatindexpath not called ios

I have created a custom tableview displayCustomUnitTableView and a custom UIView displayView and adding displayCustomUnitTableView to displayView. But i am not able to select any row in the tableView i.e., didSelectRowAtIndexPath is not called.

I am using the following code:

displayCustomUnitTableView = [[UITableView alloc]initWithFrame:CGRectMake(52.0, 110.0, 180.0, 110.0) style:UITableViewStylePlain];
displayCustomUnitTableView.delegate = self;
displayCustomUnitTableView.dataSource = self;
displayCustomUnitTableView.tag = 2;
displayCustomUnitTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
displayCustomUnitTableView.separatorColor = [UIColor blackColor];
displayCustomUnitTableView.rowHeight = 30.f;
[displayCustomUnitTableView setBackgroundColor:[ContentViewController colorFromHexString:@"#BCC9D1"]];
[displayCustomUnitTableView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
[displayCustomUnitTableView setAllowsSelection:YES];
[displayView addSubview:displayCustomUnitTableView];

Thanks in advance.

See more ..

Hide/show cells in UITableView using swift?

I have create a UITableView in IB. This view contains 5 sections and every section some cells. The first cell in some sections gives the option to the end user to show/hide the rest of the cells that belongs to the same section.

My code so far:

import UIKit

class SettingsVC: UITableViewController {

    @IBOutlet var showCallForwardSwitch: UISwitch?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func toggleValueChanged(sender: UISwitch) {

        if showCallForwardSwitch!.on {
            println("switch is on")
        } else {
            println("switch is off")
        }

        tableView.reloadData()
    }  
}

So there is only an IBOutlet and an IBAction. I can get the event via the toogleValueChanged func, however I don't know what to do from now on. Which methods to I need to use?

enter image description here

See more ..

UITableview cell Overlap on each with arm64

hi i am trying to upgrade my app to support iOS arm64 after adding arm64 Tableview cells Overlap on each (on iPhone 5s , 6 ,6+)

with arm64 after adding arm64 tabelview cells is overlapped if i remove arm64 it run correctly

See more ..

Queue of functions - Swift

I have a table in which each cell there is the profile name of a user. I want that when the profile name is clicked, it will go to the profile page of the user. I created a delegate from the cell for this. But the problem is, the variable "goToProfileVar" is empty at the starting point. Then I assign a value to it with the "goToCell103" function. Then the assigned value should be user in the "prepareforsegue" to pass the username data. The problem is that, prepareforseque functions works first and the "goToProfileVar" becomes empty, then the variable is assign to the cell.username.text.

How can I queue these functions?

 var goToProfileVar = String()
 var goToProfileVar2 = String()

func goToCell103(cell: mainCell)
{
    var goToCell103:mainCell? = cell as mainCell
    var indexPath: NSIndexPath  = self.resultsTable.indexPathForCell(goToCell103!)!

    goToProfileVar = cell.usernameLbl.text!
    goToProfileVar2 = cell.objectid.text!
           println("\(goToProfileVar) followers liked this.")
    println("\(goToProfileVar2) followers liked this.")



}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {



    if (segue.identifier == "goToProfile8") {
        var svc = segue.destinationViewController as! generalProfileLast;
        svc.dataPassed = goToProfileVar}

   else if (segue.identifier == "goToLikers1") {
        var svc = segue.destinationViewController as! likers;
        svc.dataPassed = goToProfileVar2}

    else if (segue.identifier == "goToComments1") {
        var svc = segue.destinationViewController as! enterCommentVC;
        svc.dataPassed = goToProfileVar2}

    else if (segue.identifier == "goToComments2") {
        var svc = segue.destinationViewController as! commenters;
        svc.dataPassed = goToProfileVar2}

      println("\(goToProfileVar) followers liked this very.")
     println("\(goToProfileVar2) followers liked this very.")

}

See more ..

autolayout constraints in nib not honored for UITableViewHeaderFooterView

I have a UITableView with several columns of data. The reusable cells are loaded from an xib file which has the appropriate labels and autolayout constraints. Everything works perfectly; the table columns are laid out correctly on different devices and when the devices are rotated.

The problem I am having is trying to create a table footer to show the totals of the columns in the table. I created an xib file with the same autolayout constraints as the cell xib file and am loading it in tableView.viewForFooterInSection the same way I did for the cells. As required, I am using a subclass of UITableViewHeaderFooterView instead of UITableViewCell.

The awakeFromNib method in the UITableViewHeaderFooterView subclass sets the background color, so I can see that it is the correct size on all devices/orientation, but the labels from the footer xib file are not getting laid out to match the table cells. The autolayout constraints from the footer xib file are not being honored. When I set a different background color in the footer xib file, the table footer shows this background color for the length of the xib's view.

I'm new to all of this technology and would greatly appreciate help in resolving this incredibly frustrating issue.

Is this a bug in Swift? Is there a way to use autolayout for UITableViewHeaderFooterViews loaded from nibs?

See more ..

When I add UITableView to subview, the cells aren't selectable

I have a custom class that is a subclass of UIView. I added a UITextField and a tableview as a subview. Then, in the storyboard, I set a UIView's class to the custom class.

The tableview I added in the custom class, extends larger than the initial UIView, (from the storyboard). So I changed self.frame's height.

When I run the app, I can type in the textField I added, but I can't select anything in the tableview. I can see the cells, but can't select them.

How can I make the cells selectable?

Here is the most relevant code:

_textField = [[UITextField alloc] initWithFrame:self.bounds];
[self addSubview:_textField];

CGRect tableViewsFrame = self.textField.bounds;
tableViewsFrame.origin.y += self.textField.bounds.size.height;
tableViewsFrame.size.height = 200;

_tableView = [[UITableView alloc] initWithFrame:tableViewsFrame style:UITableViewStylePlain];
[self addSubview:_tableView];

CGRect viewsFrame = self.bounds;
viewsFrame.size.height = self.textField.frame.size.height + self.tableView.frame.size.height + 100;
[self setFrame:viewsFrame];

Here is a link to a test project on jumpshare: testProject

See more ..

How to update Data in tableview using swift?

Currently I have 3 swift files: ManualViewController, AutoViewController, Main

ManualViewController is the UIViewController with a table view. AutoViewController is a UIViewController with a few buttons. Main is just a swift file with all the data for table view.

ManualViewController and AutoViewController are controlled using TabBarController.

When I run the app the initial contents found in Main.swift is loaded onto the table view. When I go to the next view i.e AutoViewController and click on a button to change data in Main.swift, the data changes. The problem is when I switch back to ManualViewController the table still contains the old data and not the updated one.

I also tried this:

override func viewWillAppear(animated: Bool) 
{
    super.viewWillAppear(false)
    self.tableView.reloadData()
}

It still din't work.

See more ..

mercredi 24 juin 2015

How to round the table view cells in ios

i want to round table-list cells either bottom or top side but not both sides can anybody please help me with example code and i have done like below but it round the both side edges but i want round only one side according to requirement(either top or bottom)

 [cell.layer setCornerRadius:7.0f];
  [cell.layer setMasksToBounds:YES];
  [cell.layer setBorderWidth:2.0f];

This above code rounds both sides cells edges but i want round at one side edge please help me somebody

See more ..

UITableView dynamic cell sizing and asynchronously loading images resulting in weird scrolling behavior

I have a UITableView + NSFetchedResultsController combination for loading comments. The comments include name, date, body, and importantly an avatar image. The comments are stored in Core Data.

Upon viewDidLoad, it checks to see if the comments have been loaded from my source. If they have not been downloaded it spawns an NSOperation to download and scrape the HTML to get the name, date, body, and URL for the avatars for each comment. It also makes the Core Data entities for all of these. Being a background threaded NSOperation, it uses a private NSManagedObjectContext to do the work and saves it back into the main MOC.

Once those are added to the store, my NSFetchedResultsController calls the delegate methods controllerWillChangeContent:, didChangeSection:, didChangeObject:, and controllerDidChangeContent:. It works fine when inserting the batch of new comments, and inserts them into the table view just fine.

My table view cells are using iOS8's UITableViewAutomaticDimension to have dynamic heights, depending on the length of content for each comment. If I only show the text of each comment (ignoring avatar images for now) everything works as expected and scrolling through comments works fine, and it all looks ordinary.

However my problem comes in when it's loading avatar images. In my configureCell: (which is called by cellForRowAtIndexPath: and controller:didChangeObject:) it checks to see if the image has been downloaded yet or not. If not, it spawns a new, different kind of NSOperation to go fetch the image based on the comment's avatarImageURL property. When it has been fetched, it adds the data of the image into the Core Data entity. It also signals the table view controller via a custom delegation method that the image has been updated. My fetched results controller also signals my table view controller view via controller:didChangeObject:.

This is where the problems come in.


When scrolling very fast, and for the first time this data is being downloaded and stored into Core Data the table view and the dynamically resizing cells act very weird. they change size many times when scrolling both up and down. And only after having scrolled through the entirety of the cells once or twice, everything is smooth after that.

When i completely disable the spawning of NSOperations to download the avatars, everything again works and scrolls fine. However, if I let it download the images and add them to the Core Data entity, but fail to implement the custom delegation method and the NSFetchedResultsChangeUpdate case for controller:didChangeObject:, it still results in the weird, choppy scrolling initially.

One thing I did notice, via NSLogs, is that all comments are inserted into the table view in a single batch, whereas every time a single avatar is downloaded, the fetched results controller will issue willChangeContent:, didChangeObject:, and didChangeContent:. Again, those three methods all for a single avatar.

Relevant methods (I can add more if necessary):

- (void)viewDidLoad {
    [super viewDidLoad];

    // First get our current array of comic infos, initiating the controller
    NSError *fetchError;
    if (![[self fetchedResultsController] performFetch:&fetchError]) {
        NSLog(@"Error in the fetched results controller: %@", fetchError.description);
        return; // Don't do anything else.
    }

    self.tableView.estimatedRowHeight = 70.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    if (self.comicInfo.comments == nil || self.comicInfo.comments.count == 0) {
        CommentsRetrieverOperation *operation = [[CommentsRetrieverOperation alloc] initWithComicInfoID:self.comicInfo.objectID];
        operation.managedObjectContext = self.managedObjectContext;
        [self.commentDownloadQueue addOperation:operation];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell" forIndexPath:indexPath];

    // Configure the cell...
    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    CommentTableViewCell *commentCell = (CommentTableViewCell *)cell;

    Comment *comment = [self.fetchedResultsController objectAtIndexPath:indexPath];

    commentCell.nameLabel.text = comment.name;
    commentCell.dateLabel.text = comment.date;
    commentCell.commentLabel.text = comment.content;
    commentCell.commentLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];

    if ([comment isAdmin].boolValue == true) {
        commentCell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"BackgroundPattern1"]];
    } else if (indexPath.row % 2 == 0) {
        commentCell.contentView.backgroundColor = [UIColor colorWithRed:248.0f/255.0f green:248.0f/255.0f blue:248.0f/255.0f alpha:1.0f];
    } else {
        commentCell.contentView.backgroundColor = [UIColor whiteColor];
    }

    if (comment.avatarImage == nil || comment.avatarImage.image == nil) {
        CommentImageDownloadOperation *operation = [[CommentImageDownloadOperation alloc] initWithCommentID:comment.objectID];
        operation.managedObjectContext = self.managedObjectContext;
        operation.delegate = self;
        operation.userInfo = @{ @"cell":commentCell, @"indexPath":indexPath };
        [self.avatarDownloadQueue addOperation:operation];
    } else {
        [self setAvatarImageForCell:commentCell withComment:comment];
    }

    commentCell.userInteractionEnabled = NO;
}

- (void)setAvatarImageForCell:(CommentTableViewCell *)cell withComment:(Comment *)comment {
    if (comment.avatarImage.isDefaultImage.boolValue) {
        cell.avatarImage = self.defaultAvatarImage;
    } else {
        UIImage *image = [UIImage imageWithData:comment.avatarImage.image];
        cell.avatarImage = image;
    }
}

- (void)commentImageDownloadOperation:(CommentImageDownloadOperation *)operation didFinishDownloadWithUserInfo:(id)userInfo {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:userInfo[@"cell"]];
    if (indexPath == userInfo[@"indexPath"]) {
        CommentTableViewCell *cell = userInfo[@"cell"];
        Comment *tempComment = (Comment *)[self.managedObjectContext objectWithID:operation.commentID];
        [self setAvatarImageForCell:cell withComment:tempComment];
    }
}

#pragma mark - Fetched Results Controller Delegate
All of these methods are copied exactly from Apple's sample at http://ift.tt/1Lq6Qac

So put shortly, my problem is that when loading images in the background for dynamically sized cells, and with using Core Data and a fetched results controller, the scrolling is very choppy. Is there a better way to implement this all, and am I implementing this wrong? Is there a better way than just loading all images at the very beginning?

See more ..

Number of lines in UILabel in self-sizing tableview cell

I have a custom UITableViewCell subclass that is using self-sizing cells. The sizing of the cells is perfect and the label is being extended correctly. However, at run time I am trying to calculate the number of lines that the label will be extended to (I need to display the line numbers next to the label), and I am not able to achieve this. I have tried the following two methods and neither seem to be returning the correct number of lines that I am seeing when the app runs:

func lineCountForText(string: String, label: UILabel) -> Int {

        let font: UIFont = UIFont(name: "SourceCodePro-Regular", size: label.font.pointSize)!

        let rect = string.boundingRectWithSize(CGSizeMake(label.frame.width, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [font : NSFontAttributeName], context: nil)

        return Int(ceil(rect.size.height/font.lineHeight))

    }

    func numberOfLinesForString(string: String, size: CGSize, font: UIFont) -> Int {
        let textStorage = NSTextStorage(string: string, attributes: [NSFontAttributeName: font])

        let textContainer = NSTextContainer(size: size)
        textContainer.lineBreakMode = .ByWordWrapping
        textContainer.maximumNumberOfLines = 0
        textContainer.lineFragmentPadding = 0

        let layoutManager = NSLayoutManager()
        layoutManager.textStorage = textStorage
        layoutManager.addTextContainer(textContainer)

        var numberOfLines = 0
        var index = 0
        var lineRange : NSRange = NSMakeRange(0, 0)
        for (; index < layoutManager.numberOfGlyphs; numberOfLines++) {
            layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)
            index = NSMaxRange(lineRange)
        }

        return numberOfLines
    }

Am I not able to do this because it is a self-sizing cell?

See more ..

how to disable didselectrowAtIndexPath when switches in tableview accessory type are ON.?

Here is my code for disabling didselectRowAtIndexPath . It disables the did select row when switch is on

But when more than on switch in accessory is on e.g. - if three switches are on and I turn off one switch , then the did select row works.

I want to disable that.

Any help ?

enter image description here

Here is my code.

     - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
       {
       if (switchControl.on) {
       NSLog(@"Switch is on");
       UIAlertView *switchAlert = [[UIAlertView alloc]initWithTitle:@"Switch is On" message:@"Please turn it off to proceed further" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
       [switchAlert show];
       }
        else{
        // table view did select working .
       }

and cellForRowAtIndexPath is -

   -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
     {
      static NSString *cellIdentifier=@"CellID";
      UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

          if (cell==nil)
         {
   cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
   cell.backgroundColor=[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:239.0/255.0 alpha:1.0];
   switchControl = [[UISwitch alloc] initWithFrame:CGRectZero];
   switchControl.tag = indexPath.row;
   cell.accessoryView = switchControl;
   [switchControl setOn:NO animated:NO];
   [switchControl addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
}}

See more ..

UITableViewCell subclass throwing an unrecognized selector sent to instance

My UITableViewCell is giving a -[UITableViewCell nameTeam]: unrecognized selector sent to instance.

I created a PlayerStatsTableViewCell.xib with a UITableViewCell and UILabel. Set the Custom Class to "PlayerStatsTableViewCell" and its Table View Cell identifier to "playerStats"

PlayerStatsTableViewCell.h

@interface PlayerStatsTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *nameTeam;
@end

PlayerStatsTableViewCell.m

@implementation PlayerStatsTableViewCell
@synthesize nameTeam;

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

In my PlayerStatsTableViewController, cell.nameTeam is throwing the error

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PlayerStatsTableViewCell *cell = (PlayerStatsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"playerStats"];
    [tableView registerNib:[UINib nibWithNibName:@"PlayerStatsTableViewCell" bundle:nil] forCellReuseIdentifier:@"playerStats"];

    cell.nameTeam.text = @"PLEASE";

    return cell;
}

See more ..

Find the UITableViewCell of an element in my Model

I would like to scroll in my tableView to a specific item. I know which item this is in my model. However, I can't be certain in which cell/indexPath it will be displayed for various reasons (the model may be filtered and sorted before displayed; the tableView may be grouped; etc.)

I was thinking of checking for the element in the cellForRowAtIndexPath tableView function and if found setting a global variable of type UITableViewCell or NSIndexPath. I'm reluctant, though, to do this - It is somewhat ugly solution due to handling global variables (not very functional / "spaghetti code".)

What is the best practice of finding the cell (or indexPath) of a specific element in my model?

See more ..

Can't scroll up/down and scroll left/right at the same time on UITableView within a UIScrollView

Update: I was able to get the table view to swipe left/right after stopping scrolling up/down by inheriting from UIScrollView and implementing the shouldRecognizeSimultaneouslyWithGestureRecognizer and shouldBeRequiredToFailByGestureRecognizer methods from UIGestureRecognizerDelegate. But I am still unable to figure out how to let the user scroll up/down or left/right after stopping the initial up/down scroll (and the user's finger is still on the device).

I created a sample project here http://ift.tt/1CuAgN8. You can test this by swiping down on the table view once, then lift your finger off and while it's still scrolling, put your finger back on to stop the scrolling. While your finger is still on the table view, try swiping left/right and it should work. But with this implementation if you try to swipe down the table view multiple times, it will sometimes get stuck because it will think that you are trying to swipe left/right. Any ideas?

Original: I have a couple UITableViews that are within a UIScrollView that has paging enabled, and is setup to let me page left and right so that only one UITableView is visible at a time. Here is a diagram (taken from Conflictive scroll on UITableView within UIScrollView)

                                 +--visible area--+  ---+
+---------`UIScrollView`---------+---------------+|  --+|
| +-------------+ +-------------+|+-------------+||  -+||
| |      0      | |      1      |||      2      |||   |||
| |`UITableView`| |`UITableView`|||`UITableView`|||  equal height
| |             | |             |||             |||   |||
| +-------------+ +-------------+|+-------------+||  -+||
+--------------------------------+---------------+|  --+| 
                                 +----------------+  ---+

What I would like to achieve is if the user scrolls down the table view, and then lifts their finger off (and the scrolling down animation is still happening), the user can chose to swipe left and right to go to the next table view. Right now if the user scrolls down the table view, and then lifts their finger off and while the scrolling down animation is still happening, and then puts their finger back on to swipe left and right, it will not allow the user to scroll left and right, and I am stuck viewing the already visible table view unless I wait for the table view scrolling to stop completely and then swipe left and right.

TL;DR Basically I cannot scroll up/down the table and swipe left/right in the scroll view at the same time, but I would like to be able to do this. An example of this would be in the iOS Instagram app on the Activity tab. You can scroll down and then swipe right while the table view is still scrolling.

See more ..

IOS download image, tableViewCell and Array

I have an Array. Inside my array have 8 object seriated:

 - text
 - text
 - link Url Image.
 - link Url Image.
 - text
 - link Url Image.
 - link Url Image.
 - text

I had downloaded all image and save to document folder. And now, How can I get all image from document folder and show in tableViewCell seriated same myArray?

I used this code to get all image from document folder.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *myPath = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *directoryContents = [fileManager contentsOfDirectoryAtPath:myPath error:nil];
NSMutableArray *subpredicates = [NSMutableArray array];
            [_arrMessageFree addObject:[NSPredicate predicateWithFormat:@"SELF ENDSWITH '.png'"]];
            [_ar addObject:[NSPredicate predicateWithFormat:@"SELF ENDSWITH '.jpg'"]];
NSPredicate *filter = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];

NSArray *onlyImages = [directoryContents filteredArrayUsingPredicate:filter];

But, I cannot show both text and image seriated in myArray.

See more ..

Register collection view cells in table view cell

I have a table view cell with collection view in it. Collection view requires to register xibs of its own cells. I can't figure it out where should I place code for registering collection view cells xibs.

I tried to place it in awakeFromNib() and init(), but it doesn't work.

let photoCollectionViewCellID = "photoCollectionViewCellID"
let addPhotoCollectionViewCellID = "AddPhotoCollectionViewCell"

class PhotosTableViewCell: UITableViewCell {

    @IBOutlet weak var collectionView: DynamicCollectionView!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        let nibName = UINib(nibName: photoCollectionViewCellID, bundle:nil)
        collectionView!.registerNib(nibName, forCellWithReuseIdentifier: photoCollectionViewCellID)
        //
        let nibName2 = UINib(nibName: addPhotoCollectionViewCellID, bundle:nil)
        collectionView!.registerNib(nibName2, forCellWithReuseIdentifier: addPhotoCollectionViewCellID)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        println("init photo cell")
    }

    func setCollectionViewDataSourceDelegate(dataSourceDelegate delegate: protocol<UICollectionViewDelegate,UICollectionViewDataSource>) {
        let nibName = UINib(nibName: photoCollectionViewCellID, bundle:nil)
        collectionView!.registerNib(nibName, forCellWithReuseIdentifier: photoCollectionViewCellID)

        let nibName2 = UINib(nibName: addPhotoCollectionViewCellID, bundle:nil)
        collectionView!.registerNib(nibName2, forCellWithReuseIdentifier: addPhotoCollectionViewCellID)

        collectionView.dataSource = delegate
        collectionView.delegate = delegate
        collectionView.reloadData()
    }
}

See more ..

How to Update Managed Object Data Passed from Controller with NSFetchRequest

I am new to iOS development (3 weeks in) and I have started my first core data application. It has two Entities, Folder and List. The storyboard has three view controllers, the first a table view for folders, second for the folder overview and make changes, third is a table view for the list of items.

The first view controller displays all the folders in a tableview, which I can add to and it reloads the data. This works fine because It uses the fetch request to pollute the table.

However when segueing to another view controller via the table cell I pass on the selected Folder data to the controller using the index path. e.g.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "showDetails" {
        let destinationVC = segue.destinationViewController as! FolderDetailsViewController
        let indexPath = UITable.indexPathForSelectedRow()
        let selectedFolder = folders[indexPath!.row]
        destinationVC.selectedFolder = selectedEvent        
    }
 }

This means when editing the details of the folder in the second controller (via a modal) to view changes I have to go back to the first controller to reload the data and tap again. This is because I have no NSFetchRequestto see if changes were made. How can I use NSFetchRequest to reload the data of the selectedFolder passed from the first controller ?

My second view controller works with the data passed from the first table view:

    var selectedFolder: Folder!
    folderNameLabel.text = selectedFolder?.title
    folderDetailsLabel.text = selectedFolder?.details
    folderDateLabel.text = displayDate

Then my third populates the table with the ordered set of the Folder.

   var selectedFolder: Folder!

    //add ordered set to an array
    var listArray = [List]()

    var unsortedList = NSMutableArray()
    for singleItem in selectedFolder.list {
        let loopNote = singleItem as! List
        unsortedList.addObject(loopNote)
    }
    let sortDescriptor = NSSortDescriptor(key: "item", ascending: true)
    checklistArray = unsortedList.sortedArrayUsingDescriptors([sortDescriptor]) as! [List]

    //Load data to table view cell cell 
    cell.textLabel?.text = listArray[indexPath.row].item

(PS:I have been doing a lot of reading on this but all the tutorials I am seeing work with one view controller and don't pass on the data. Any help or guidance would be much appreciated, have been stuck for a couple days)

See more ..

How to save tableview rows to a file and reload to tableview

I have a simple tableview and I populated it with a text.field :

@interface ListaDeProdutosTableViewController ()

@property NSMutableArray *produtos;

@end

@implementation ListaDeProdutosTableViewController

Now I want to save this rows to a file (to persist data) and read it back to tableview. How can I do this?

Can you help me? Thank you!

See more ..

When adding subview, the view is in the wrong position

I have a custom class that is a subclass of UITextField. In layoutSubviews, I want to add a UIView at the same position of self.frame. The textField I'm adding this custom class to, is in a cell in a UITableViewController. I did the following:

CGRect rect = self.frame;
UIView *myView = [[UIView alloc] initWithFrame:rect];
[self addSubview:myView];

When I run the app, myView is not at the same position as the textField. What am I doing wrong, and how can I make myView to be at the same position as the textField?

See more ..

Multiple Selection Delete with NSPredicate error in numberOfRowsInSection:

I'm having difficulties updating the numberOfRowsInSection: method after I update an array from the documents folder. I know its something simple, but I think I've just been staring at it for too long to find the solution. I've tried beginUpdates and endUpdates.

Basically, the only time it crashes is when I filter the plist with an NSPredicate. Otherwise, if the category 'show all' is selected I can delete all the rows with no crash.

-(void)viewDidLoad {

    NSArray *array = [[NSArray arrayWithArray:[self returnArrayFromPlist]] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    self.alertSubArray = [[NSMutableArray alloc] init];
    self.alertSubArray = [NSMutableArray arrayWithArray:array];

    catName = @"ALL"; //Set on load, which loads all items in plist without filtering

    //Creating a horizontal menu to filter the array based on the button they select
        UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
        myButton.frame = CGRectMake(5,self.scrollView.frame.size.height / 2 -10,100,20);     [myButton setTitle:@"ALL" forState:UIControlStateNormal];
        [myButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
        [myButton setTitleColor:[UIColor colorWithRed:(66/255.0) green:(106/255.0) blue:(140/255.0) alpha:1] forState:UIControlStateNormal];
        [myButton setTitleColor:[UIColor colorWithRed:(48/255.0) green:(144/255.0) blue:(251/255.0) alpha:1] forState:UIControlStateSelected];
        [myButton addTarget:self action:@selector(cmdCategroy:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:myButton];
        myButton.tag = self.categoryArray.count + 1; //setting tag


    for (int y = 0; y < self.categoryArray.count; y++) {
        UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
        myButton.frame = CGRectMake(100 + 5 + 100 * y,self.scrollView.frame.size.height / 2 -10,100,20);
        [myButton setTitle:[self.categoryArray objectAtIndex:y] forState:UIControlStateNormal];
        [myButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
        [myButton setTitleColor:[UIColor colorWithRed:(66/255.0) green:(106/255.0) blue:(140/255.0) alpha:1] forState:UIControlStateNormal];
        [myButton setTitleColor:[UIColor colorWithRed:(48/255.0) green:(144/255.0) blue:(251/255.0) alpha:1] forState:UIControlStateSelected];
        [myButton addTarget:self action:@selector(cmdCategroy:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:myButton];
        myButton.tag = y; //setting tag for all buttons not 'ALL'
}

//Handle selection of respective button

-(void)cmdCategroy:(id)sender {

   NSInteger tid = ((UIControl *) sender).tag;

   if (tid != self.categoryArray.count + 1) {
    catName = [self.categoryArray objectAtIndex:tid];
    [self filterContentForCategory:catName];
   } else {
    //Selected category is 'ALL' <- different then loading with 'ALL' this is when a user deliberately tap on 'ALL'
    catName = @"ALL";
    NSArray *array = [[NSArray arrayWithArray:[self returnArrayFromPlist]] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    self.alertSubArray = [NSMutableArray arrayWithArray:array];

    if (self.alertSubArray.count >= 1) {
        [self.editButton setEnabled:YES];
        [self.editButton setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
    } else {
        [self.editButton setEnabled:NO];
        [self.editButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
}
 [self.tableView reloadData];
}

If Button is NOT 'ALL', then filter :

-(void)filterContentForCategory:(NSString*)category {

NSPredicate *resultPredicate;
if ([category isEqualToString:@"A"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"blah"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"B"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"blah2 "];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"C"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"blah3"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"D"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"blah4"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"E"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"blah5"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"F"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"blah6"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"G"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"blah7"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"H"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"(SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@)", @"blah", @"blah",@"blah", @"blah", @"blah", @"blah",@"blah",@"blah",@"blah"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"I"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"(SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@)", @"blah9", @"blah9"];
    [self filterResultsWithPredicate:resultPredicate];
} else if ([category isEqualToString:@"J"]) {
    resultPredicate = [NSPredicate predicateWithFormat:@"(SELF BEGINSWITH[c] %@) OR (SELF BEGINSWITH[c] %@)", @"blah", @"blah"];
    [self filterResultsWithPredicate:resultPredicate];
}

}

- (void)filterResultsWithPredicate:(NSPredicate *)predicate {
//Get original array from documents folder so we don't refilter a filtered array
NSArray *filteredResults = [[[self returnArrayFromPlist] filteredArrayUsingPredicate:predicate] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

self.alertSubArray = [NSMutableArray arrayWithArray:filteredResults];

if (filteredResults.count >= 1) {
    [self.editButton setEnabled:YES];
    [self.editButton setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
} else {
    [self.editButton setEnabled:NO];
    [self.editButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
}
}

UITableView delegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.alertSubArray.count;
}

Deleting actual selected rows

- (IBAction)deleteButton:(id)sender {
    if ([self.deleteButton.titleLabel.text isEqualToString:@"Done"]) {
      //Dismiss view
} else {
    // Delete all the selected rows
    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];

    BOOL deleteSpecificRows = selectedRows.count > 0;
    if (deleteSpecificRows)
    {
        NSMutableArray *stringsOfObjects = [NSMutableArray new];
        for (NSIndexPath *selectionIndex in selectedRows) {
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectionIndex];
            [stringsOfObjects addObject:cell.textLabel.text];
        }
             NSLog(@"stringsOfObjects (selected objects) array %@", stringsOfObjects);


        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [paths objectAtIndex:0];

        NSString *plistPath = [path stringByAppendingPathComponent:@"AlertSubscriptions.plist"];

        NSMutableArray *array = [[[NSMutableArray alloc] initWithContentsOfFile:plistPath] mutableCopy];

        [array removeObjectsInArray:stringsOfObjects];
        //removing objects from original array of plist
        [array writeToFile:plistPath atomically:YES];
        //Create a new array from the array minus selected/removed objects
        self.alertSubArray = [NSMutableArray new];
        self.alertSubArray = [NSMutableArray arrayWithArray:array];
        NSLog(@"new array is %@", self.alertSubArray); // returns exactly as wanted

        // Tell the tableView that we deleted the objects
        [self.tableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic]; //works but crashes here with incorrect numberOfRows number

    }
    else
    {

    }

    // Exit editing mode after the deletion.
    [self.tableView setEditing:NO animated:YES];
    [self updateButtonsToMatchTableState]; //Make buttons enabled again

}

}

Again, this all works exactly as wanted until a different menu item is selected. So it's clearly something to do with the filtering. Any help is appreciated

See more ..

Get superView of custom class

I have a custom class myCustomClass which is a subclass of UITextField. (I'm going to call myCustomClass in a viewControllers class.)

In myCustomClass, I'm trying to check what kind of viewController the class that called it is. (UIViewController, UITableViewController etc.)

I tried:

if ([self.superview.nextResponder isKindOfClass[UIViewController class]]) {
    NSLog(@"View Controller");
} else if ([self.superview.nextResponder isKindOfClass[UITableViewController class]) {
    NSLog(@"TableView Controller");
}

I only get a result if the superclass is a viewController. So I did the following:

NSLog(@"%@", self.superview.nextResponder);

Results

UIViewController Class - ViewController

UITableViewController Class - UITableViewCell

How can I check if it's a UITableViewController?

See more ..

How to have multiple table views in a Master-Detail application?

Scenario

I would like to mimic the stock Mail app in iOS. In the Mail app you can select an inbox account (1st UITableView), select an email from a list (2nd UITableView) and finally be presented with your selected email (Detail View Controller).

To do that, the template that best fits this layout is "Master-Detail". This template comes out of the box with a single UITableView. I would like, however, to add an extra UITableView in my app because one is not enough. How would I go about doing that?

My approach

I placed a new UITableView in my Storyboard and connected it with a UINavigationController using the "Relationship root view controller" segue. I then connected the 1st UITableView to the UINavigationController I just created using the "show" segue. Finally, I I subclassed a new UITableView class for the 2nd table view, I added cells and reusable identifiers).

What's not working

When I tap cells in the 1st UITableView, they just highlight. I cannot access the 2nd UITableView. Do I have to use the prepareForSegue method? Here's the code I used so far. SecondController is the 2nd UITableView.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        if let indexPath = self.tableView.indexPathForSelectedRow {
            let object = objects[indexPath.row] as! String
            if let navController = (segue.destinationViewController as? UINavigationController) {
                let controller = navController.topViewController as! SecondController
                controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()
            }
        }
    }
}

How to have multiple table views in a Master-Detail application?

See more ..

Looping Through UITableView with custom UITableViewCells

I'm making an app with a settings page that is set up as a UITableView with custom cells. These cells are set up like this:

I need to loop through a table of these cells each time one of the switches is changed. Here is the code I was trying to use to do this:

for var x = 0; x < preferredDistances.count; x++ {

            var indexPath = NSIndexPath(forRow: x, inSection: 0)

            let cell : SettingsCell = settingsTable.cellForRowAtIndexPath(indexPath) as! SettingsCell

            if cell.settingsCellSwitch.on {
                preferredDistances.append(cell.settingsCellLabel.text!)
            }

        }

When trying to loop through the UITableView with this code, my cell return nil. What am I doing wrong in this block of code and how can I fix it?

See more ..

UIRefreshControl methods do nothing in Swift

I am giving my first steps with Swift, and in this case I am trying to implement a UITableViewController. I have subclassed the table view controller and 'Enabled' its Refreshing parameter in IB.

My problem is that calling beginRefreshing or endRefreshing do absolutely nothing to the refresh control. I have been using refresh controls successfully in ObjC, so there must be something I still don't get right in my implementation. Below is my code for the subclass of the table view controller:

import UIKit

class ConcertsViewController: UITableViewController {
    @IBOutlet var concertsTable: UITableView!
    var concerts: [ConcertModel]?

    override func viewDidLoad() {
        super.viewDidLoad()

        //configures refresh control
        self.refreshControl?.addTarget(self, action: "refreshTable:", forControlEvents: UIControlEvents.ValueChanged)
        self.refreshControl?.beginRefreshing()
        getAllConcerts()
    }

    private func getAllConcerts(){

        ConcertModel.getAllConcerts { (concerts, response, error) -> Void in
            self.concerts = concerts
        }
    }

    func refreshTable(refreshControl: UIRefreshControl){
        refreshControl.endRefreshing()
    }

}

See more ..

iOS - Whitespace appearing in iPhone 6 and 6+

While testing my app, some whitespace appears only in iPhone 6 and 6+.

Some info about the setting

My app storyboards are designed for iPhone 4s, I've added launch images in @3x (1242*2208) and @2x (750*1334) in images.xcassets and added an image named Default-568h@2x.png (this one was first 720*1280 and currently 1080*1920 for a reason I'm currently asking myself) in app files.

Edit: I have auto layout, use size classes options is disabled.

I don't have any problems with iPhone4s or iPhone5. I've already fixed the black bars at top and bottom of the app-thingy.

Problem definition

But when it comes to the iPhone6 and 6+, poof. App opens but has a white frame in bottom and right corner.

I'm adding some screenshots to show the problem thoroughly.

These two belong to iPhone 5.

iPhone5-1

Background is fading here, view is totally normal.

iPhone5-2

And now, for something completely different:
iPhone6-1

See those lines? Navigation bar and tableview stops there, but tab bar is functioning right.

iPhone6-2

In here, the switch is slided a bit. But the total view is not bad.

So, what did I miss?

See more ..

SWIFT sorting cells that have a collection of different objects by a specific object

So basically, I have a function that calls a JSON web service, and uses SwiftyJSON to collect all the info I need to populate my tableview, as well as other info I need for my DetailViewController. Some examples of the information I collected were the title of the entry, time, ID, and magnitude. I would like to know how I can sort my tableView so that the first cell shows the highest magnitude, all the way down to the last cell showing lowest magnitude.

I've been searching for a way to do this, but I hadn't had much luck because the way the JSON is formatted, it's an array of 50 dictionaries. My collection of Magnitudes are 50 strings, not in an array.

Here's my code:

  var info = [AppModel]()



    func getEarthquakeInfo(completion: (results : NSArray?) ->Void ){


        DataManager.getEarthquakeDataFromFileWithSuccess {
            (data) -> Void in

                let json = JSON(data: data)


                if var JsonArray =  json.array {
                    JsonArray.removeAtIndex(0)

                    for appDict in JsonArray {
                        // parsing
                        var ids: String? = appDict["id"].stringValue
                        var title: String? = appDict["title"].stringValue
                        var time: String? = appDict["time"].stringValue
                        var lattitude: String? = appDict["lat"].stringValue
                        var longitude: String? = appDict["lng"].stringValue
                        var north: String? = appDict["north"].stringValue
                        var west: String? =  appDict["west"].stringValue
                        var mag: String? = appDict["mag"].stringValue
                        var depth: String? = appDict["depth"].stringValue
                        var timeStamp: String? = appDict["timestamp"].stringValue
                        // Splitting up title string into 2 parts
                        let newString = title!.stringByReplacingOccurrencesOfString("  ", withString: " - ", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        var title2strings = newString.componentsSeparatedByString(" - ")
                        var scale = title2strings[0]
                        var location = title2strings[1]
                        // replacing M in scale string with Richter Scale
                        let scaleString = scale.stringByReplacingOccurrencesOfString("ML", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        let scaleString2 = scaleString.stringByReplacingOccurrencesOfString("mb", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        let scaleString3 = scaleString2.stringByReplacingOccurrencesOfString("Mw", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                         let scaleString4 = scaleString3.stringByReplacingOccurrencesOfString("MD", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        let scaleString5 = scaleString4.stringByReplacingOccurrencesOfString("M", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        //Formatting the date
                        var date = NSDate(dateString: time!).getDatePart()
                        // sorting

                        // Collecting all the information
                        var information = AppModel(idEarth: ids, title: title, time: date, lat: lattitude, lng: longitude, north: north!, west: west, mag: mag, depth: depth, timeStamp: timeStamp, location: location, scale: scaleString5)


                        self.info.append(information)
                        completion(results: self.info)
                    }


            }

        }

    }




    override func viewDidLoad() {
        super.viewDidLoad()
        //register custom cell

        getEarthquakeInfo { (info) in
            self.tableView.reloadData()


            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()

            }
        }


    }




    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->   UITableViewCell {
        let cell: TheCustomCellTableViewCell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath) as TheCustomCellTableViewCell
        cell.Location.text = info[indexPath.row].location
        cell.Scale.text = info[indexPath.row].scale
        cell.Time.text = info[indexPath.row].time
        return cell

    }

If anyone could just point me in the right direction on how to do this, I'd appreciate it.

See more ..

Populate table view from Struct

I have a Struct such as:

struct Test {
            var name: String?
            var value: Float?
            var isfavorite:String? 


    init(name: String, value: Float, favorite: String){

        self.name = name
        self.value = rawRate
        self.favorite = favorite
    }
}

And a String in wich I stored a string according to the Test Struct

var TestInformation = [String:Test]()

When I want to populate a tableview based on the content of TestInformation I get the following error:

[String : Test]' does not have a member named 'name'

Here is the line I use to populate the tableview:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

            cell.testlabel?.text =  TestInformation[indexPath.row].name
}

I don't understand what I am doing wrong, maybe someone point me to right direction.

Thank you :)

Edit :

I add information to testInformation by doing the following:

let testInformation =  [
    Test(name: "Foo1", value: 1.32, isfavorite: "favorite"),
    Test(name: "Foo2", value: 1.27, isfavorite: "favorite")]

See more ..

What is the clearsSelectionOnViewWillAppear property for?

clearsSelectionOnViewWillAppear is a boolean property of UITableViews and UICollectionViews. It's set on true by default. According to the Apple Reference clearsSelectionOnViewWillAppear is

a Boolean value indicating if the controller clears the selection when the table appears.

This is still not clear to me. I suppose "clearing the selection" means that the UITableView does not have any selected (highlighted) UITableViewCells when the UITableView receives a viewWillAppear: message. I do not think this is the right answer, though.

What is the clearsSelectionOnViewWillAppear property for?

See more ..

Why does my UITableView content 'jump up' when trying to scroll up the table?

I have a really weird UITableView issue. Upon initial load, it'll fetch say 10 rows. Everything is fine. I can scroll down and up.

However, if I call an additional data fetch to be added to the current data, I get an issue when trying to scroll the tableview back up.

Here's what I do

  • Fetch 10 rows on viewDidLoad. Scroll to bottom, and wait...
  • After 5 seconds, 10 more rows will be added via -performSelector: withObject: afterDelay:
  • Attempt to scroll back up (finger moving down, showing above content, rows 9, 8, 7, ... 2, 1).
  • However, after this second fetch, the UITableView no longer scrolls properly. It jumps like crazy. For example, say the tableView is 500 height. And the top of the 9th row is at Y=50. I draw my finger down 10px, and the top of the 9th row is Y=60, and the bottom of the 8th is starting to reveal itself. I continue dragging my finger in one slow and continuos pace. 20px, 30px, 40px, etc. All of a sudden, at some random point, say 100px (Top of 9th row is at Y=150), BOOM, the content jumps. The top of the 9th row is no longer at Y=150, but at perhaps Y=70. This happens over and over. Continue to drag your finger down, the content will come with for a bit, and then seemingly at random, it jumps back up.

Have you ever seen this?

A couple of things

1) I can rule out it being the # of cells in the table. If I decide to fetch 25 rows on first fetch it'll be fine. It's not until I do that second fetch that this becomes an issue. (Making think it can't likely be anything in the uitableview delegate/datasource methods). If I fetch 5 rows on first fetch, it'll be fine. Fetch 5 more 5 seconds later, and the issue begins.

Other relevant information could be that I'm using self sizing cells.

Here's the relevant code I would think. Any ideas?

- (void)viewDidLoad
{
    [super viewDidLoad];
    ...
    [self fetchQuestionsAndClearExistingOnSuccess:NO];
    [self performSelector:@selector(loadMore) withObject:self afterDelay:7.0];
}

- (void)fetchQuestionsAndClearExistingOnSuccess:(BOOL)clear withCompletion:(void (^)(void))completion 
{
    NSString *userIdParam = [NSString stringWithFormat:@"user_id=%@&page=%d", (User *)[[UserManager sharedManager] getUser].userId, self.nextPageToRequest];

    [[ServerAccessAndCoreDataLayer sharedCDL] getQuestionsWithParamString:userIdParam andCompletion:^(BOOL success, NSArray *resultArray, NSInteger statusCode, NSArray *messages, NSArray *errors) {
        if (completion) {
            completion();
        }

        if (success) {
            if (clear) {
                [self.questions removeAllObjects];
            }
            self.nextPageToRequest++;
            [self loadQuestions:resultArray];
        }
        else {
            [self.tableView reloadData];
        }
    }];
}

- (void)loadQuestions:(NSArray *)resultArray 
{
    if (resultArray.count > 0) {
        for (Question *question in resultArray) {
            if (![self.questions containsObject:question]) {
                [self.questions addObject:question];
            }
        }

        [self.tableView reloadData];
    }
    else {
        self.endOfQuestionsReached = YES;
    }
}

See more ..

Swift - Table View Black Screen?

I'm trying to present the TableViewController after the user is done sharing with the ActivityViewController. Here's my method for that :

 @IBAction func share(sender: UIBarButtonItem) {
        var   memeedimage = generateMemedImage()

        let activityViewController = UIActivityViewController(activityItems:[memeedimage] , applicationActivities: nil)
        presentViewController(activityViewController, animated: true, completion: nil)

        activityViewController.completionWithItemsHandler = {
            (activity, success, returneditems, error) in
            println("Activity: \(activity) Success: \(success) Items: \(returneditems) Error: \(error)")
            self.save()
            activityViewController.dismissViewControllerAnimated(true, completion: nil)


            let memevc:MemeTableViewController  = MemeTableViewController()
            self.presentViewController(memevc, animated: true, completion: nil)
        }

I already dismissed the activityviewcontroller and the self.presentviewcontroller is referring to the viewthatcontroller that presented the activityViewController . However, I just get a black screen once the user is done sharing.

Why is this? I believe it's because my tableview did not load properly.

Here's my MemeTableViewController code :

import UIKit

class MemeTableViewController : UIViewController,UITableViewDelegate,UITableViewDataSource
{
    var memesz: [MemeObject]!

    @IBOutlet var tableView: UITableView!

    override func viewWillAppear(animated: Bool) {            
            super.viewWillAppear(animated)
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            memesz = appDelegate.memes
            //tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.hidesBarsOnSwipe = true
        navigationController?.hidesBarsOnTap = true            
    }

    //reserves the number of rows needed to display the image
       func tableView(tableView : UITableView, numberOfRowsInSection section : Int)->Int
       {
            println("ARE YOU SERIOUS")
            return memesz.count
        }

    //Reserves the row to be dequeued for display
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {            
        let cell:TableViewzCell = tableView.dequeueReusableCellWithIdentifier("MemesCell", forIndexPath: indexPath) as! TableViewzCell
        let memezrow =  memesz[indexPath.row]
        cell.label1.text = memezrow.textFieldtop
        cell.label2.text = memezrow.textFieldbottom
        cell.imageview.image = memezrow.memedImage
        println("Why is this not being called")

            return cell
    }

    //Method to do something when the row is selected
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let detailController = self.storyboard!.instantiateViewControllerWithIdentifier("FullScreenMeme") as! FullScreenMeme
        detailController.meme = memesz[indexPath.row]
        self.navigationController!.pushViewController(detailController, animated: true)
        println("This too")
    }
}

See more ..

cell.textLabel.text repeats in every section of UITableView

I'm setting up the way texLabel of a UITableViewCell is determined in cellForRowAtIndexPath, and the problem is that when pulling from agendaTableArray, it repeats the item in every section of the table, rather than only in the section it belongs to. In other words, I want each item in the array to be a row in its own section.

Here's how it currently looks:

enter image description here

Here's how I'm setting up cellForRowAtIndexPath:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier];
        cell.textLabel.text = nil;
    }

    self.agendaTableArray = @[@"Dinner with Rebekah", @"Soccer game", @"Denist appt.", @"Celebrate job offer, drinks with Pierre!", @"No events today!"];

    // Set title of the event
    if (self.datePicked == [NSNumber numberWithInt:16]) {
        NSLog(@"cellForRowAtIndexPath says self.datePicked is 16");
    }
    else if (self.datePicked == [NSNumber numberWithInt:17]) {
        NSLog(@"cellForRowAtIndexPath says self.datePicked is 17");
    }
    else if (self.datePicked == [NSNumber numberWithInt:18]) {
        NSLog(@"cellForRowAtIndexPath says self.datePicked is 18");
    }
    else if (self.datePicked == [NSNumber numberWithInt:19]) {
        NSLog(@"cellForRowAtIndexPath says self.datePicked is 19");
    }
    else {

    }

    cell.textLabel.text = self.agendaTableArray[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14];

    [self whatSectionsAreVisible];

    return cell;
}

How can I set it to only load the item from agendaTableArray in the first section's cell?

See more ..

Why does UINavigationController have an unexpected size inside a container view?

I am working on a iOS (Swift) project. I am trying to embed a UINavigationController inside a container view. As seen:

Hierarchy

It goes: UITabBarController -> UIViewController: container view -> UINavigationController -> UIViewController

I have hidden the Navigation Bar and Toolbar for the UINavigationController

Everytime I run it, I am getting this result (the red is the container views background)

Result

Why is this happening? and how can I get rid of the red bar and make the tableview fill the whole container view?

BTW: If I embed the table view to the container view directly, I don't have this problem. It only seems to happen when using a navigation controller.

See more ..

Static table view with uitableviewclass

I added a Table View Controller in to my storyboard. I changed the content to Static Cells and added some rows with section. After that I connect the Table View Controller with a UITableViewController Class and build the app. But the problem i, it won't work. Why? Can I not use a UITableViewController class for a Static Table View?

See more ..

iOS: UIButton background image getting removed for button in custom uitableviewcell on scroll

I have a uibutton in my custom table view cell which has different background image for a button for different cell. As soon as i start scrolling, random cells which were out of scope removes their background image. I have two button with two background image but it is always doing for one of them

Here is an example

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
...
PlayerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"playerCell"];
    if(cell == nil) {

        NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PlayerTableViewCell" owner:self options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[PlayerTableViewCell class]])
                cell = (PlayerTableViewCell *)currentObject;
        }
    }
numberImage = [self getUserImage:[self._collectionsNewGame[indexPath.row -1] objectForKey:@"hostBirthday"] isSign:false];
            signImage =[self getUserImage:[self._collectionsNewGame[indexPath.row -1] objectForKey:@"hostBirthday"] isSign:true];
cell.numberButton setBackgroundImage:[UIImage imageNamed:numberImage] forState:UIControlStateNormal];
        [cell.signButton setBackgroundImage:[UIImage imageNamed:signImage] forState:UIControlStateNormal];
...
...
}

Please Help

See more ..

UITableViewCell Subclass with custom init method

I'm creating a custom UITableViewCell and I would like to create a custom init method so that I can inject some data (an array) to it. Every time I do this however I get a crash on the init method itself. What is the best way to accomplish this? Any help would be greatly appreciated.

Here is my code for cellForRowAtIndex:

 // Setup Jam Object
    PFObject* jamObject = [postsArray objectAtIndex:indexPath.section];
    Jam *jam = [[Jam alloc] initWithJamObject:jamObject];

    cellIdentifier = @"MainCell";

    Post_MainCell *cell = (Post_MainCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell.contentView.backgroundColor = UIColorFromRGB(0xDBDBDB);
    cell.parentTableViewController = self;
    cell.jam = jam;
    [cell initialize];

    return cell;

What I would like to do is create an init method so I can pass in the Jam object on initialization. Something like this:

-(id)initWithFrame:(CGRect)frame andJam:(Jam *)jam {
self = [super initWithFrame:frame];
if (self)
{
    self.jam = jam;
}

return self;
}

See more ..

How can I populate one UITableView with two queries?

I have a tableview that needs to display all friend requests that a user is involved in (both sent and received.)

However, the only way I can think of to do this is to perform two separate queries: one where the username is equal to the requester, and one where the username is equal to the requested.

Is this the best route to go? If so, how do I set up the code?

My code keeps crashing the app on func cellForRowAtIndexPath() on let dateString3 = timePeriodFormatter.stringFromDate(pendingDates[indexPath.row]) saying that the array is out of range.

This is what I have so far:

@IBOutlet weak var tableView: UITableView!

override func viewWillAppear(animated: Bool) {

    UIApplication.sharedApplication().beginIgnoringInteractionEvents()

    users = []
    user = PFUser()
    objectId = String()
    pendingDates = []
    username = String()
    usernames = []
    tradeIdentifier = String()
    tradeId = []
    pendingRequestsId = []

    var requestsQuery = PFQuery(className: "Requests")
    requestsQuery.whereKey("status", equalTo: "transit")
    requestsQuery.whereKey("completed", notEqualTo: PFUser.currentUser()!.username!)
    requestsQuery.whereKey("completed", notEqualTo: "complete")
    requestsQuery.whereKey("requestedUsername", equalTo: PFUser.currentUser()!.username!)
    requestsQuery.orderByDescending("createdAt")
    requestsQuery.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {
            if let objects = objects as? [PFObject] {
                for object in objects {
                    pendingDates.append(object.createdAt! as NSDate)
                    usernames.append(object["requesterUsername"] as! String)
                    users.append(object["requester"] as! PFUser)
                    pendingRequestsId.append(object.objectId!)
                    tradeId.append("requested")
                }
            }
            var requestsQuery2 = PFQuery(className: "Requests")
            requestsQuery2.whereKey("status", equalTo: "transit")
            requestsQuery2.whereKey("completed", notEqualTo: PFUser.currentUser()!.username!)
            requestsQuery2.whereKey("completed", notEqualTo: "complete")
            requestsQuery2.whereKey("requesterUsername", equalTo: PFUser.currentUser()!.username!)
            requestsQuery2.orderByDescending("createdAt")
            requestsQuery2.findObjectsInBackgroundWithBlock {
                (objects: [AnyObject]?, error: NSError?) -> Void in
                if error == nil {
                    if let objects = objects as? [PFObject] {
                        for object in objects {
                            pendingDates.append(object.createdAt! as NSDate)
                            usernames.append(object["requestedUsername"] as! String)
                            users.append(object["requested"] as! PFUser)
                            pendingRequestsId.append(object.objectId!)
                            tradeId.append("requester")

                        }
                    }
                    UIApplication.sharedApplication().endIgnoringInteractionEvents()
                } else {
                    UIApplication.sharedApplication().endIgnoringInteractionEvents()
                    println(error)
                }
                //self.tableView.reloadData()
            }
        } else {
            println(error)
        }
        self.tableView.reloadData()
    }


}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return usernames.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: PendingTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! PendingTableViewCell

    cell.username.text = usernames[indexPath.row] as String

    let timePeriodFormatter = NSDateFormatter()
    timePeriodFormatter.dateFormat = "EEE, MMM d"

    let dateString3 = timePeriodFormatter.stringFromDate(pendingDates[indexPath.row])

    cell.date.text = dateString3

    return cell

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    username = usernames[indexPath.row]
    objectId = pendingRequestsId[indexPath.row] as String
    tradeIdentifier = tradeId[indexPath.row]
    user = users[indexPath.row]
    self.performSegueWithIdentifier("showDetails", sender: self)        
}

See more ..

Show data in Custom tableview Cell

I am new to developing. i have some experience but i'm not great at it (yet). I'm working on this tableview app which shows data. I want to show that data in a custom cell. But i don't know how to do that. This is the code i use for my tableview:

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryViewTableCell"];
    if (cell == nil) {

        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"HistoryViewTableCell" owner:self options:nil];

        cell = [topLevelObjects objectAtIndex:0];
    }
    NSDictionary * tempDictionary = [tableData objectAtIndex:indexPath.row];
    cell.textLabel.text = [tempDictionary objectForKey:@"PickupAddress"];

    return cell;
}

I need to show this line of code in my custom cell.

cell.textLabel.text = [tempDictionary objectForKey:@"PickupAddress"];

I already made a class and a xib file for the custom cell

See more ..

swift IOS 8 NSInvalidArgumentException, why?

Here is my problem, I'm trying to make a clon of snapchat very simple one, using parse with the default project given in the page, everything was going ok, until I have to take pictures and save them to send them to an user. With this code:

//
//  UsersTableViewController.swift
//  SnapClomSwift
//
//  Created by Pedro Alonso on 24/06/15.
//  Copyright (c) 2015 Parse. All rights reserved.
//

import UIKit
import Parse

class UsersTableViewController: UITableViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {


    var usersArray: [String] = []

    var activeRecipient: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        var query = PFUser.query()
        query?.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)

        var users = query?.findObjects()

        if let user = users {
            for username in user {
                println(username.username!!)

                usersArray.append(username.username!!)


            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return usersArray.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("snapCell", forIndexPath: indexPath) as! UITableViewCell

        // Configure the cell...
        cell.textLabel?.text = usersArray[indexPath.row]

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        activeRecipient = indexPath.row

        pickImage()


    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {

        //Upload image to parse //error come somewhere from here I think


        println("Image Selected")
        self.dismissViewControllerAnimated(true, completion: nil)


        var imageToSend = PFObject(className:"Image")
        imageToSend["image"] = UIImageJPEGRepresentation(image, 0.5)
        imageToSend["senderUsername"] = PFUser.currentUser()!.username
        imageToSend["recipientUsername"] = usersArray[activeRecipient]

        imageToSend.save()

    }

    func pickImage() {

        var image = UIImagePickerController()
        image.delegate = self
        image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        image.allowsEditing = false

        self.presentViewController(image, animated: true, completion: nil)

    }


}

The error:

2015-06-24 15:03:13.414 SnapClomSwift[2043:124661] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableData PF_base64EncodedString]: unrecognized selector sent to instance 0x7a648960'

Is not very helpful to debug, any help??

See more ..

Swift: Place UITableViewCell beneath siblings

I'm trying to build a custom UITableView that acts in a similar way to the reminders app.

Instead of the top-most visible cell scrolling off the display, I want it to be covered by the next cell so the cells appear to stack on top of one another as you scroll.

Currently I am using

override func scrollViewDidScroll(scrollView: UIScrollView) {

  let topIndexPath: NSIndexPath = tableView.indexPathsForVisibleRows()?.first as! NSIndexPath

  let topCell = tableView.cellForRowAtIndexPath(topIndexPath)

  let frame = topCell!.frame

  topCell!.frame = CGRectMake(frame.origin.x, scrollView.contentOffset.y, frame.size.width, frame.size.height)
}

But the top cell is always above the second cell - causing the second cell to scroll under it.

Also if I scroll quickly this seems to misplace all of my cells.

See more ..

UILabel and UITextField overlapping in the same cell

In one UITableViewCell I have UILabel and UITextField like this:

http://ift.tt/1TKXDgc

As you can see the UITextField is aligned to the right. After I write something in the text field it overlaps.

How can I avoid this?

And this code snippets are how to fill cell

cell.textLabel.text = R_NAME_CLIENT_NAME;
        self->clientNameLabel = cell.textLabel;
       [self createTextField:&clientName WithDefaultText:@"none" WithText:@"" InCell:cell IndexPath:indexPath];

  • (void) createTextField:(UITextField**)textField WithDefaultText:(NSString*)defaultText WithText:(NSString*)text InCell:(UITableViewCell*)cell IndexPath:(NSIndexPath*)indexPath{ *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 11, cell.frame.size.width - 20, 20)]; (*textField).font = [UIFont fontWithName:@"Arial-ItalicMT" size:17]; }

Possible duplicate did not help me.

See more ..