Можно ли показать изображение в UIAlertView?
38122 просмотра
9 ответа
Можно ли добавить изображение в UIAlertView, например, показать изображение из файла plist?
Автор: summer Источник Размещён: 12.11.2019 09:53Ответы (9)
43 плюса
Вы можете сделать это как:
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(220, 10, 40, 40)];
NSString *path = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"smile.png"]];
UIImage *bkgImg = [[UIImage alloc] initWithContentsOfFile:path];
[imageView setImage:bkgImg];
[successAlert addSubview:imageView];
[successAlert show];
Это добавит изображение в правом углу вашего предупреждения, вы можете изменить изображение кадра для перемещения.
Надеюсь это поможет.
Автор: Madhup Singh Yadav Размещён: 24.02.2010 04:3910 плюса
в iOS 7 или выше используйте этот код
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 282)];
UIImage *wonImage = [UIImage imageNamed:@"iberrys.png"];
imageView.contentMode=UIViewContentModeCenter;
[imageView setImage:wonImage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Arirang List"
message:@"phiên bản: 1.0\n website: www.iberrys.com\n email: quangminh@berrys.com\nmobile: 0918 956 456"
delegate:self
cancelButtonTitle:@"Đồng ý"
otherButtonTitles: nil];
//check if os version is 7 or above
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
[alertView setValue:imageView forKey:@"accessoryView"];
}else{
[alertView addSubview:imageView];
}
[alertView show];
Автор: Quang Minh
Размещён: 02.01.2015 10:36
5 плюса
Вам нужно будет создать подкласс UIAlertView и немного изменить его подпредставления. Есть несколько обучающих программ для такого рода вещей:
- Пользовательский UIAlertView (вероятно, наиболее подходит для вашей проблемы)
- Пользовательский UIAlertView с TableView (также очень удобно)
5 плюса
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:@"your Title" message:@"Your Message" delegate:nil cancelButtonTitle:@"Your Title" otherButtonTitles:nil];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 40, 40)];
NSString *loc = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Your Image Name"]];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:loc];
[image setImage:img];
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
[Alert setValue:image forKey:@"accessoryView"];
}else{
[Alert addSubview:image];
}
[Alert show];
Автор: Anbu.Karthik
Размещён: 03.10.2013 05:16
2 плюса
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 282)];
UIImage *wonImage = [UIImage imageNamed:@"iberrys.png"];
imageView.contentMode = UIViewContentModeCenter;
[imageView setImage:wonImage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Arirang List"
message:@"phiên bản: 1.0\n website: www.iberrys.com\n email: quangminh@berrys.com\nmobile: 0918 956 456"
delegate:self
cancelButtonTitle:@"Đồng ý"
otherButtonTitles:nil];
//check if os version is 7 or above
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
[alertView setValue:imageView forKey:@"accessoryView"];
} else {
[alertView addSubview:imageView];
}
[alertView show];
Автор: user9235122
Размещён: 18.01.2018 02:21
0 плюса
Я сделал некоторые изменения для решения, предоставленного Madhup.
Решение от Madhup прекрасно работает для коротких сообщений, однако, когда сообщение слишком длинное, сообщение будет покрыто изображением.
Следовательно, я добавил следующие шаги в метод UIAlertViewDelegate - (void) willPresentAlertView: (UIAlertView *) alertView
Добавьте 8 "\ n" в качестве префикса сообщения, чтобы отправить сообщение вниз, зарезервировав место для изображения (мое изображение было ограничено в 100x150)
Определите подпредставления AlertView, чтобы узнать, существует ли UITextView.
UITextView будет существовать только тогда, когда сообщение слишком длинное.
Если UITextView не существует, все будет хорошо, изображение показано хорошо, сообщение показано хорошо.
Если UITextView существует, удалите префикс 8 «\ n» из UITextView.text, а затем вызовите UITextView.setFrame для изменения размера и изменения положения UITextview.
Вышеуказанное действие отлично работает.
Я посылаю NSDictionary в качестве сообщения, которое будет показано, словарь содержит 2 пары ключ-значение, "msg" => строка реального сообщения. "url" => как изображение с веб-сайта.
С помощью метода NSURLConnection sendSynchronousRequest код будет извлекать данные изображения из Интернета в пути.
- (void)showAlertView:(NSDictionary *)msgDic {
NSLog(@"msgDic = %@", msgDic);
NSMutableString *msg = [[NSMutableString alloc] initWithString:@"\n\n\n\n\n\n\n\n"];
if ([msgDic objectForKey:@"msg"]) {
[msg appendFormat:@"%@", [msgDic objectForKey:@"msg"]];
}
else {
[msg setString:[msgDic objectForKey:@"msg"]];
}
NSLog(@"msg = %@", msg);
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Alert Title"
message:msg
delegate:self
cancelButtonTitle:@"Close" otherButtonTitles:nil];
if ([msgDic objectForKey:@"url"]) {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[msgDic objectForKey:@"url"]]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
NSData *imgData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (imgData) {
UIImage *shownImage = [UIImage imageWithData:imgData];
UIImageView *imgView = [[UIImageView alloc] initWithImage:shownImage];
[imgView setFrame:CGRectMake(floor(284-100)/2.0, 47, 100, 150)];
[alert addSubview:imgView];
[imgView release];
}
}
alert.delegate = self;
[alert show];
[alert release];
[msgDic release];
}
- (void)willPresentAlertView:(UIAlertView *)alertView {
int viewCount = [alertView.subviews count];
NSLog(@"subviews count = %i", viewCount);
if (viewCount > 0) {
BOOL bFoundTextView = NO;
for (int count=0; count<=[alertView.subviews count] -1; count++) {
BOOL bIsTextView = NO;
UIView *subView = [alertView.subviews objectAtIndex:count];
NSLog(@"view index %i classname = %@", count, [[subView class] description]);
bIsTextView = [[[subView class] description] isEqualToString:@"UIAlertTextView"];
bFoundTextView |= bIsTextView;
if (bIsTextView) {
UITextView *textView = (UITextView *)subView;
NSMutableString *msg = [[NSMutableString alloc] initWithString:textView.text];
[msg setString:[msg substringFromIndex:8]];
textView.text = msg;
CGRect frame = textView.frame;
if (frame.origin.y != 205) {
frame.origin.y = 205;
frame.size.height -= 155;
[textView setFrame:frame];
}
[msg release];
}
}
}
}
Автор: Dennies Chang
Размещён: 29.03.2012 06:07
0 плюса
Примечание для IOS 7 и выше
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
[alert setValue:imageView forKey:@"accessoryView"];
}else{
[alert addSubview:imageView];
}
Автор: Ryan Heitner
Размещён: 13.11.2014 07:56
0 плюса
Swift версия:
let alertView = UIAlertView(title: "Alert", message: "Alert + Image", delegate: nil, cancelButtonTitle: "OK")
let imvImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
imvImage.contentMode = UIViewContentMode.Center
imvImage.image = UIImage(named: "image_name")
alertView.setValue(imvImage, forKey: "accessoryView")
alertView.show()
Автор: Nguyễn Ngọc Bạn
Размещён: 11.08.2015 05:05
-1 плюса
Используя чистый макет:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hello"
message:nil
preferredStyle:UIAlertControllerStyleAlert];
UIImage *image = // target image here;
CGSize size = image.size;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, size.width, size.height)];
imageView.image = image;
[alertController.view addSubview:imageView];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:leftMargin];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:topMargin];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:rightMargin];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:bottomMargin];
[imageView autoSetDimension:ALDimensionWidth toSize:size.width];
[imageView autoSetDimension:ALDimensionHeight toSize:size.height];
// add desired actions here
[self presentViewController:alertController animated:YES completion:nil];
Автор: user1232690
Размещён: 06.03.2017 12:28
Вопросы из категории :
- objective-c Приложение для iPhone в ландшафтном режиме, системы 2008
- objective-c Как программно отправить смс на айфон?
- objective-c Открытие нестандартного URL в приложении Какао
- objective-c Каков наилучший способ перетащить NSMutableArray?
- objective-c Как работает пул автозапуска NSAutoreleasePool?
- objective-c Как вы можете создать Makefile из проекта Xcode?
- iphone Как мне дать моим веб-сайтам значок для iPhone?
- iphone iPhone веб-приложения, шаблоны, рамки?
- iphone Приложение для iPhone, которое получает доступ к структуре Core Location через Интернет
- iphone Tips for a successful AppStore submission?
- iphone Могу ли я написать нативные приложения для iPhone с использованием Python
- iphone Изучение OpenGL ES 1.x
- uialertview Можно ли показать изображение в UIAlertView?
- uialertview Пользовательский AlertView с фоном
- uialertview Как отключить опцию копирования и вставки из UITextField программно
- uialertview Изменить размер UIAlertView
- uialertview Xcode 4.2, UIAlertView и UIAlertButton?
- uialertview Добавить UIDatePicker в UIAlertView