简体   繁体   中英

How to get the position of a table view's subview before it's displayed?

I've tried searching for this on SO, but no luck finding something that works for my situation.

Here is my hierarchy and what I'm trying to do:

//     ->  view
//     -> ->  myLabel           //I'd like to have this match center.x with...
//     -> ->  tableView
//     -> -> ->  tableViewCell
//     -> -> -> ->  UIStackView
//     -> -> -> -> ->  mySwitch    //...this, before everything appears

Any suggestions on how to achieve this? All help is very appreciated. Thanks!


EDIT: This code works on the positioning, but doesn't run before it appears. It runs when a cell has to get loaded/reused, so it first appears in the wrong spot:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as? myCell {
        cell.configureCell(myArray[indexPath.row])
        let centerPoint = cell.mySwitch.convertPoint(cell.mySwitch.center, toView: self.view)
        myLabel.center.x = centerPoint.x - (myLabel.frame.width / 2)
        return cell
    } else {
       return myCell()
    }
}

i'm not sure i understand your question, but you can try to use

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

you can get the refer to cell and use cell.yourSwitch.frame.origin for position

UPDATE: Thanks everyone for the help. For anyone interested, I gave up and resorted to using the size classes in interface builder, though it would have been more ideal to do it programmatically (Keeps things cleaner IMO, as opposed to having to tailor it to each size class. Now the two items aren't actually constrained to each other, I positioned them manually). Leaving this question open for any other readers who would like to comment or read!

Based on your comments this is what you should do (although I don't recommended because it will affect the performance of your app)

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
    //Option 1
    (cell as! MyCell).mySwitch...

    //Option 2
    let cell: MyCell = cell as! MyCell
    cell.mySwitch...
}

But if I understood correctly and all the switches are positioned at the same level in every cell all you need to do is position the label in the same way you positioned everything else so it will look aligned with the switches without the need of actually tying them together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM