2014-12-23 18 views
23

Tôi đã tạo UIAlertView chứa UIActivityIndicator. Mọi thứ hoạt động tốt, nhưng tôi cũng muốn UIAlertView biến mất sau 5 giây.Loại bỏ UIAlertView sau 5 giây Swift

Tôi làm cách nào để loại bỏ UIAlertView của mình sau 5 giây?

var alert: UIAlertView = UIAlertView(title: "Loading", message: "Please wait...", delegate: nil, cancelButtonTitle: "Cancel"); 

var loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(50, 10, 37, 37)) as UIActivityIndicatorView 
loadingIndicator.center = self.view.center; 
loadingIndicator.hidesWhenStopped = true 
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray 
loadingIndicator.startAnimating(); 

alert.setValue(loadingIndicator, forKey: "accessoryView") 
loadingIndicator.startAnimating() 

alert.show() 
+0

Nếu bạn đang tải một cái gì đó, tại sao bạn muốn ẩn cảnh báo sau một thời gian cố định? Bạn sẽ không giấu nó khi tải xong? – drewag

Trả lời

39

Bạn có thể bỏ UIAlertView sau 5 giây bạn lập trình, như vậy:

alert.show() 

// Delay the dismissal by 5 seconds 
let delay = 5.0 * Double(NSEC_PER_SEC) 
var time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) 
dispatch_after(time, dispatch_get_main_queue(), { 
    alert.dismissWithClickedButtonIndex(-1, animated: true) 
}) 
+0

Không cần tạo hàm thứ hai. Bên trong khối 'dispatch_after' đơn giản gọi là' alert.dismissWithClickedButtonIndex (-1, animated: true) ' – rmaddy

+0

@rmaddy Rất đúng. –

+0

BTW - Tôi thích cách tiếp cận này tốt hơn so với sử dụng bộ hẹn giờ. – rmaddy

6

Tạo đối tượng cảnh báo như là một biến toàn cầu. Bạn có thể sử dụng NSTimer cho mục đích này.

var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false) 


func dismissAlert() 
{ 
    // Dismiss the alert from here 
    alertView.dismissWithClickedButtonIndex(0, animated: true) 

} 

LƯU Ý:

Chú ý: UIAlertView bị phản đối trong iOS 8. (Lưu ý rằng UIAlertViewDelegate cũng bị phản đối). Để tạo và quản lý báo trong iOS 8 và sau đó, thay vì sử dụng UIAlertController với preferredStyle của UIAlertControllerStyleAlert.

tham khảo: UIAlertView

13

trong nhanh chóng 2 bạn có thể làm điều này. Tín dụng để @Lyndsey Scott

let alertController = UIAlertController(title: "youTitle", message: "YourMessage", preferredStyle: .Alert) 
       self.presentViewController(alertController, animated: true, completion: nil) 
       let delay = 5.0 * Double(NSEC_PER_SEC) 
       let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) 
       dispatch_after(time, dispatch_get_main_queue(), { 
        alertController.dismissViewControllerAnimated(true, completion: nil) 
       }) 
+0

Điều gì xảy ra là có nút ok trên cảnh báo và người dùng nhấp vào nút đó trước khi công văn được thực thi? –

+0

Điều gì xảy ra nếu? Hãy thử nó và xem những gì sẽ xảy ra. Tôi không hiểu câu hỏi ... –

+0

Tôi đã tự hỏi nếu nó sẽ sụp đổ kể từ khi alertControler sẽ đã bị sa thải nếu người dùng presed nút ok trước khi chậm trễ 5 giây. Tôi đã thử nó và tôi không nhận được bất kỳ thông báo lỗi nào. Vì vậy, tôi đoán nó là ok. –

44

Một giải pháp để sa thải một cảnh báo tự động trong Swift 3Swift 4 (Lấy cảm hứng từ một phần của những câu trả lời: [1], [2], [3]):

// the alert view 
let alert = UIAlertController(title: "", message: "alert disappears after 5 seconds", preferredStyle: .alert) 
self.present(alert, animated: true, completion: nil) 

// change to desired number of seconds (in this case 5 seconds) 
let when = DispatchTime.now() + 5 
DispatchQueue.main.asyncAfter(deadline: when){ 
    // your code with delay 
    alert.dismiss(animated: true, completion: nil) 
} 

Kết quả:

enter image description here

+2

Rất cám ơn ... nó đã giúp tôi .. –

1

Đối Swift 3

let alert = UIAlertController(title: “Alert”, message: “Message”,preferredStyle: UIAlertControllerStyle.alert) 
self.present(alert, animated: true, completion: nil) 
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(5.0 * Double(NSEC_PER_SEC)))/Double(NSEC_PER_SEC), execute: {() -> Void in 
    alert.dismiss(animated: true, completion: {() -> Void in 
}) 
}) 
0

// Generic Function Ví Sa thải cảnh báo wrt hẹn giờ

/** showWithTimer */ 
public func showWithTimer(message : String?, viewController : UIViewController?) { 

    let version : NSString = UIDevice.current.systemVersion as NSString 
    if version.doubleValue >= 8 { 
     alert = UIAlertController(title: "", message: message, preferredStyle:.alert) 
     viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil) 
     let when = DispatchTime.now() + 5 
     DispatchQueue.main.asyncAfter(deadline: when){ 
      self.alert?.dismiss(animated: true, completion: nil) 
     } 
    } 
} 
0

Đối nhanh chóng 4 bạn có thể sử dụng mã này

let alertController = UIAlertController(title:"Alert",message:nil,preferredStyle:.alert) 
self.present(alertController,animated:true,completion:{Timer.scheduledTimer(withTimeInterval: 5, repeats:false, block: {_ in 
    self.dismiss(animated: true, completion: nil) 
})} 
Các vấn đề liên quan