Proper way to determine UITableViewCell width for grouped custom cells?

不想你离开。 提交于 2020-01-02 05:38:10

问题


I have a custom UITableViewCell created through code (not Interface Builder). I have sub-views that rely on the width of the cell: there is a label that always needs to be just inside the right edge of the cell. The cells appear in a grouped table view.

I had originally hard-coded the values to work with iPhone, but now I'm converting the app to a universal binary and the hard-coded numbers are out for grouped table views on the iPad.

Is there a proper way to get the width of the cell? The frame returns the full screen width, which is throwing my labels out of place. Or should I just hard-code two sets of values, one for iPhone and one for iPad?

Any suggestions would be greatly appreciated.


回答1:


You should be able to get the appropriate dimensions from the cell's contentView subview. But you should normally just set the sizes and autoresizing masks on your subviews so that the cell will appear correctly no matter what the specific width ends up being.




回答2:


None of this seemed to work for me; I have a custom cell defined in a xib with a graphic against the left hand edge (20px in on iPhone), looked fine on iPhone. But on iPad the graphic was overlapping the left grouped section border! To fix it I set an outlet on the Horizontal Space constraint (leading) to the image, then tweaked that in the code for the UITableViewCell subclass:

- (void)setFrame:(CGRect)frame {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        self.leadingSpaceConstraint.constant = 40;
    }
    [super setFrame:frame];
}

And fiddled the number until the gap was just right. :)

I realise setFrame: may not have been the ideal place for this code, but it worked- so it stayed.



来源:https://stackoverflow.com/questions/5228020/proper-way-to-determine-uitableviewcell-width-for-grouped-custom-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!