Как изменить высоту UIPickerView

Вы не получили исключение только потому, что до того, как возникло исключение, ваша система акторов была прервана, а затем приложение закрывается.

Попробуйте добавить Thread.sleep(1000) перед actorSystem.terminate(), вы увидите исключение.

Кстати: это поведение не связано с if you use only one actor or with a child. Вы получаете исключение, если используете ребенка только потому, что это случайное поведение, связанное с временной последовательностью.

113
задан TheNeil 20 May 2019 в 19:30
поделиться

8 ответов

Кажется очевидным, что Apple особенно не приглашает унавоживание с высотой по умолчанию эти UIPickerView, но я нашел, что можно достигнуть изменения в высота из представления, беря на себя полное управление и передавая размер нужного кадра во время создания, например:

smallerPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 120.0)];

Вы обнаружите, что на различных высотах и ширинах, существуют визуальные незначительные сбои. Очевидно, эти незначительные сбои должны были бы или работаться вокруг так или иначе или выбрать другой размер, который не показывает их.

54
ответ дан Fabio Cardoso 24 November 2019 в 02:41
поделиться

См. мой ответ на этот вопрос: UIPicker, измеряющий в альбомном режиме

0
ответ дан Community 24 November 2019 в 02:41
поделиться

Насколько я знаю, невозможно уменьшить UIPickerView. Я также на самом деле не видел более короткий, используемый нигде. Мое предположение - то, что это была пользовательская реализация, если им действительно удавалось уменьшить его.

0
ответ дан NilObject 24 November 2019 в 02:41
поделиться

У меня есть обнаружил, что вы можете редактировать размер UIPickerView - только не с помощью построителя интерфейса. откройте файл .xib с помощью текстового редактора и установите любой размер окна выбора. Конструктор интерфейсов не сбрасывает размер и вроде работает. Я уверен, что Apple заблокировала размер не зря, поэтому вам придется поэкспериментировать с разными размерами, чтобы увидеть, что работает.

10
ответ дан 24 November 2019 в 02:41
поделиться

Wenn Sie Ihre Auswahl in IB erstellen möchten, können Sie die Größe nachträglich auf eine kleinere Größe ändern. Überprüfen Sie, ob es immer noch richtig zeichnet, da es einen Punkt gibt, an dem es abscheulich aussieht.

0
ответ дан 24 November 2019 в 02:41
поделиться

Ни один из вышеперечисленных подходов не работает в iOS 4.0

Высота pickerView больше не изменяется по размеру. Есть сообщение, которое выводится в консоль при попытке изменить рамку пикера в 4.0:

-[UIPickerView setFrame:]: invalid height value 66.0 pinned to 162.0 

Я закончил тем, что сделал нечто довольно радикальное, чтобы получить эффект меньшего пикера, который работает как в OS 3.xx, так и в OS 4.0. Я оставил пикер любого размера, какой решит SDK, и вместо этого сделал на фоновом изображении прозрачное окно, через которое пикер становится видимым. Затем просто поместил пикер позади (в порядке Z) моего фонового UIImageView так, чтобы была видна только часть пикера, которая диктуется прозрачным окном на моем фоне.

46
ответ дан 24 November 2019 в 02:41
поделиться

Хорошо, после долгой борьбы с дурацким выбором в iOS 4 я решил изменить свой элемент управления на простую таблицу: вот код:

ComboBoxView.m = which is actually looks more like pickerview.

//
//  ComboBoxView.m
//  iTrophy
//
//  Created by Gal Blank on 8/18/10.
//

#import "ComboBoxView.h"
#import "AwardsStruct.h"


@implementation ComboBoxView

@synthesize displayedObjects;

#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle

/*
- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    return [[self displayedObjects] count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


    NSString *MyIdentifier = [NSString stringWithFormat:@"MyIdentifier %i", indexPath.row];

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
        //cell.contentView.frame = CGRectMake(0, 0, 230.0,16);
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 5, 230.0,19)] autorelease];
        VivatAwardsStruct *vType = [displayedObjects objectAtIndex:indexPath.row];
        NSString *section = [vType awardType]; 
        label.tag = 1;
        label.font = [UIFont systemFontOfSize:17.0];
        label.text = section;
        label.textAlignment = UITextAlignmentCenter;
        label.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
        label.adjustsFontSizeToFitWidth=YES;
        label.textColor = [UIColor blackColor];
        //label.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:label]; 
        //UIImage *image = nil;
        label.backgroundColor = [UIColor whiteColor];
        //image = [awards awardImage];
        //image = [image imageScaledToSize:CGSizeMake(32.0, 32.0)];

        //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        //UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        //cell.accessoryView = imageView;
        //[imageView release];
    }

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

Вот для этого файл .h:

//
//  ComboBoxView.h
//  iTrophy
//
//  Created by Gal Blank on 8/18/10.
//

#import <UIKit/UIKit.h>


@interface ComboBoxView : UITableViewController {
    NSMutableArray *displayedObjects;
}

@property (nonatomic, retain) NSMutableArray *displayedObjects;


@end

now, in the ViewController where I had Apple UIPickerView I replaced with my own ComboBox view and made it size what ever I wish.

ComboBoxView *mypickerholder = [[ComboBoxView alloc] init]; 
[mypickerholder.view setFrame:CGRectMake(50, 220, 230, 80)];
[mypickerholder setDisplayedObjects:awardTypesArray];

вот и все, теперь осталось только создать переменную-член в представлении поля со списком, которая будет содержать текущий выбор строки, и мы в порядке идти.

Всем понравиться.

1
ответ дан 24 November 2019 в 02:41
поделиться

Даже если это не изменение размера, другая уловка может помочь в ситуации, когда UIPicker расположен внизу экрана.

Можно попробовать сдвинуть его немного вниз, но центральный ряд должен оставаться видимым. Это поможет открыть некоторое пространство над средством выбора, поскольку нижние строки будут за пределами экрана.

Я повторяю, что это не способ изменения высоты представления UIPicker, а некоторое представление о том, что вы можете сделать, если все остальные попытки потерпят неудачу.

1
ответ дан 24 November 2019 в 02:41
поделиться