Можно ли добавить изображение в UIAlertView, например, показ изображения из файла plist?Можно ли показать изображение в UIAlertView?
ответ
Вы можете сделать это:
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];
Это добавит изображение в правом углу вашего предупреждения, вы можете изменить изображение рамки для перемещения.
Надеюсь, это поможет.
Вам нужно подклассифицировать UIAlertView и немного перестроить его подпрограммы. Есть несколько учебных пособий для такого рода вещь:
- Custom UIAlertView (вероятно, наиболее применим к вашей проблеме)
- Custom UIAlertView w/ TableView (очень удобных)
Но я думаю, что переставлять подвидов может привести к отказу приложения. –
Первая ссылка не работает. –
Я сделал некоторые изменения для решения, предоставленного Madhup.
Решение от Madhup отлично работает для короткого сообщения, однако , когда сообщение слишком длинное, сообщение будет покрыто изображением.
Таким образом, я добавил следующие шаги в методе UIAlertViewDelegate - (Недействительными) willPresentAlertView: (UIAlertView *) alertView
Добавить 8 "\ п" в качестве префикса сообщения, чтобы подтолкнуть сообщение вниз , резервирование места для изображения (мое изображение было ограничено в 100x150)
Обнаружить подпункты AlertView, чтобы узнать, существует ли UITextView.
UITextView будет существовать только в том случае, если сообщение слишком длинное.
Если UITextView не существует, все будет хорошо, изображение показано хорошо, сообщение показано хорошо.
Если UITextView существует, удалите 8 префикс «\ n» из UITextView.text, , а затем вызовите UITextView.setFrame для изменения размера и изменения положения UITextview.
Вышеуказанное действие работает нормально.
Я отправляю NSDictionary как отображаемое сообщение, словарь содержит 2 пары ключ-значение, "msg" => настоящую строку сообщения. "url" => как изображение с веб-сайта.
С помощью метода sendSynchronousRequest NSURLConnection код будет извлекать данные изображения из Интернета по пути.
- (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];
}
}
}
}
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];
http://stackoverflow.com/questions/18729220/uialertview-addsubview-in-ios7 – user3182143
[alertView setValue: imageView forKey: @ "accessoryView"]; – user3182143
[action setValue: принадлежностиImage forKey: @ "image"]; – user3182143
Примечание для IOS 7 и выше
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
[alert setValue:imageView forKey:@"accessoryView"];
}else{
[alert addSubview:imageView];
}
в прошивке 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: [email protected]\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];
@QuangMing ваш кодовый вызов UIAlertview 2 раза. И я не понимаю, почему? – Muju
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()
Как настроить размер вида предупреждения или аксессуара? Если я использую вышеуказанный код, предупреждение отображается для полного размера – AAA
по умолчанию, они не предоставляют какой-либо способ его настройки. Если вы хотите гораздо больше пользовательских, вы должны создать настраиваемый контроллер предупреждений. (это подкласс класса uiviewcontroller) –
Использование чистого макета стручка:
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];
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: [email protected]\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];
- 1. UIAlertView можно ли поставить изображение в качестве заголовка?
- 2. Показать UIAlertView
- 3. Изображение в uialertview ...?
- 4. Можно ли отключить подсказку Touch ID (UIAlertview)?
- 5. Возможно ли показать UIAlertView внутри конкретного UIView?
- 6. Показать UIAlertView на заставке
- 7. Как показать время в UIAlertView?
- 8. Как добавить изображение в UIAlertView?
- 9. Показать UIAlertView перед запуском UIImagePickerController
- 10. UIAlertView в UIAlertView
- 11. Можно ли показать изображение с помощью формообразователя Yii CForm?
- 12. Показать UIAlertView и клавиатура одновременно
- 13. Можно ли вставить изображение в другое изображение в Polymer?
- 14. Можно ли переместить в UIAlertView с левого экрана?
- 15. Можно ли показать изображение без его фона с помощью CSS?
- 16. Показать UIAlertView из UITableViewCell в TableView
- 17. Показать UIAlertView при нажатии UIBarButtonItem
- 18. Показать UIAlertView на определенную дату?
- 19. Показать UIAlertView с закрытой заявкой
- 20. Можно отображать содержимое html в iOS7 UIAlertView?
- 21. Как показать текстовое изображение можно щелкнуть?
- 22. Показать UIAlertView или UIViewController в Логотипе Tweak
- 23. показать UIAlertView, когда в приложении выполняется покупка
- 24. Как показать UIAlertView в классе NSObject?
- 25. Цель c показать значение NSDictionary в UIAlertView
- 26. Можно ли проверить, существует ли дублирующее изображение в списке?
- 27. Как добавить изображение с текстом в UIAlertView?
- 28. Есть ли способ показать сообщение (например, UIAlertView) из модального UIPopover?
- 29. Можно ли получить доступ к тегу UIAlertView с помощью тега?
- 30. Можно ли отображать встроенное изображение?
работает отлично .. спасибо! но если я сместил изображение в центр, он будет заблокирован сообщением. Как я могу сделать это таким образом, чтобы изображение находилось в центре, а ниже изображения было сообщение? – summer
Единственное, что вы можете сделать, это добавить еще одну метку для сообщения и добавить \ n \ n \ n ... в конце заголовка. Это единственный способ узнать, что не использует не документированные функции. –
Будет ли яблоко одобрять приложение, если вы добавите изображения в UIAlertView? – Illep