如何获得UIAlertController的帧宽?

我想获得UIAlertController框架的宽度,以便我可以指定UIPlertController附带的UIPickerView和UIToolbar的宽度。

我试图使用以下语句来获取宽度。

alertPicker.view.frame.size.width

但是,宽度与viewController的相同:

self.view.frame.size.width

有没有想过获得UIAlertController的宽度? 非常感谢。

这是我的代码。

UIAlertController *alertPicker = [UIAlertController alertControllerWithTitle:nil message:@"\n\n\n\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet]; CGRect pickerFrame = CGRectMake(8, 0, alertPicker.view.frame.size.width, self.view.frame.size.height/2); UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame]; pickerView.showsSelectionIndicator = YES; pickerView.dataSource = self; pickerView.delegate = self; UIToolbar* pickerToolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(2, 0, alertPicker.view.frame.size.width, 44)]; UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(doneBtnisClicked:)]; UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; pickerToolbar.items = [[NSArray alloc] initWithObjects:flexSpace,doneBtn,nil]; [alertPicker.view addSubview:pickerToolbar]; [alertPicker.view addSubview:pickerView]; 

UIAlertControllerinheritance自UIViewController ,因此您可以获得UIAlertControllerUIView的大小并获得宽度。

UIAlertController的可见宽度是UIWindow的宽度(纵向模式)减去每侧10个填充点,无论设备方向如何

UIAlertController

斯威夫特4

  let alertController = UIAlertController(title:"Title", message: "Message", preferredStyle: .alert) print(alertController.view.frame.size.width - 20.0)