我有一个自定义 UITableViewCell
在通用应用程序中,我必须为 iPhone 和 iPad 设置不同的框架,我必须考虑不同的方向但无法识别设备的方向。 UIDeviceOrientation
是在错误的地方? UIDeviceOrientation
返回 0
.
这是 CustomCell.m
中的代码
-(void) layoutCellPortrait{
if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){
//......frame subviews iPhone
}else{
//........frame subviews Ipad
}
}
-(void) layoutCellLandscape{
if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){
//.....frame subviews iPhone
}else{
//.......frame subviews Ipad
}
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice]orientation];
NSLog(@"The orientation is è %d", deviceOrientation);//here return 0
if(deviceOrientation == UIInterfaceOrientationPortrait || deviceOrientation== UIInterfaceOrientationPortraitUpsideDown) {
[self layoutCellPortrait];
}
else if (deviceOrientation== UIInterfaceOrientationLandscapeRight){
[self layoutCellLandscape];
}
else if (deviceOrientation==UIInterfaceOrientationLandscapeLeft){
[self layoutCellLandscape];
}
[self.contentView addSubview:self.subviews];
}
return self;
}
最佳答案
在你的类中实现旋转委托(delegate),每当发生旋转时,调用单元类中的一个方法,并以此方向作为输入参数(假设你在表上调用 reloadData
,而该表又调用此方法,该方法位于 cellForRowAtIndexpath
方法中。这个应在每次旋转中相应地重置框架。
更新:
在轮值代表中,
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration {
self.interfaceOrientation = orientation;
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
[self.tableView reloadData];
}
在 tableView
cellForRowAtIndexPath
方法中,- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
//code..
[cell rearrangeSubviewsForOrientation:self.interfaceOrientation];
return cell;
}
在你的
cell
类中添加这个,- (void)rearrangeSubviewsForOrientation:(UIInterfaceOrientation)orientation {
if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){
//iPhone
if(orientation == UIInterfaceOrientationPortrait || orientation== UIInterfaceOrientationPortraitUpsideDown) {
//portait
} else {
//landscape
}
} else {
//iPad
if(orientation == UIInterfaceOrientationPortrait || orientation== UIInterfaceOrientationPortraitUpsideDown) {
//portait
} else {
//landscape
}
}
}
关于iphone - 如何在 UITableViewCell 的子类中管理旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13026118/