2016-05-24 15 views
8

Il carattere personalizzato UIAlertController non funziona.Il carattere personalizzato UIAlertController non funziona su iOS

Il seguente codice è una funzione ShowActionSheetAsync, mostra ActionSheet. A questo punto, voglio cambiare il carattere di ActionSheet. Ho provato diversi modi, ma non ha funzionato bene. C'è una buona soluzione?

public Task<bool> ShowActionSheetAsync() 
{ 
    var source = new TaskCompletionSource<bool>(); 
    var alert = new UIAlertController 
    { 
     Title = "title" 
    }; 
    alert.AddAction(UIAlertAction.Create(
      "button1", 
      UIAlertActionStyle.Default, 
      _ => source.SetResult(true))); 
    alert.AddAction(UIAlertAction.Create(
     "cancel", 
     UIAlertActionStyle.Cancel, 
     _ => source.SetResult(false))); 

    // [Block 1] 
    var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController; 
    ViewController.PresentViewController(alert, true, delegate 
    { 
     // [Block 2] 
    }); 

    // [Block 3] 
    return source.Task; 
} 

Primo tentativo Il seguente codice non funziona correttamente.

  • Quando ho messo il codice a [Block 1] o [Block 2]

    • Non funziona affatto
  • Quando ho messo il codice a [Block 3]

    • Si applica solo quando il primo spettacolo ActionSheet. Dal secondo volte, non funziona

UILabel.AppearanceWhenContainedIn(typeof(UIActionSheet)).Font = UIFont.FromName(StyleResources.MediumFontName, 20);

Il secondo tentativo Il seguente codice, inoltre, non funziona correttamente.

  • Quando ho messo il codice a [Block 2]

    • Dopo aver mostrato il carattere predefinito per un breve periodo, mostrando il carattere personalizzato
  • Quando ho messo il codice a [Block 3]

    • funziona solo suPulsante

è un metodo di estensione per UIView e restituisce tutti i Bambini del tipo appropriato.

var labels = alert.View.FindDescendantViews<UILabel>(); 
foreach (var label in labels) 
{ 
    label.Font = UIFont.FromName(StyleResources.MediumFontName, 20); 
} 
+0

Ti sei stancato con 'label.Font = UIFont (nome: StyleResources.MediumFontName, dimensione: 20)'? –

+0

Qual è la differenza con il mio secondo tentativo e il tuo codice? @JigarTarsariya – wplong11

+0

Hai esaminato il [protocollo UIAppearance] (http://stackoverflow.com/a/30463812/2518285)? –

risposta

1

UIAlertControllerUILabels carattere e il colore possono essere impostati tramite KVC utilizzando il tasto attributedTitle. Utilizzare questo in [Block 3]

func changeAlert(alert: UIAlertController, backgroundColor: UIColor, textColor: UIColor, buttonColor: UIColor?) { 
    let view = alert.view.firstSubview().firstSubview() 
    view.backgroundColor = backgroundColor 
    view.layer.cornerRadius = 10.0 

    // set color to UILabel font 
    setSubviewLabelsToTextColor(textColor, view: view) 

    // set font to alert via KVC, otherwise it'll get overwritten 
    let titleAttributed = NSMutableAttributedString(
     string: alert.title!, 
     attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(17)]) 
    alert.setValue(titleAttributed, forKey: "attributedTitle") 


    let messageAttributed = NSMutableAttributedString(
     string: alert.message!, 
     attributes: [NSFontAttributeName:UIFont.systemFontOfSize(13)]) 
    alert.setValue(messageAttributed, forKey: "attributedMessage") 


    // set the buttons to non-blue, if we have buttons 
    if let buttonColor = buttonColor { 
     alert.view.tintColor = buttonColor 
    } 
} 

func setSubviewLabelsToTextColor(textColor: UIColor, view:UIView) { 
    for subview in view.subviews { 
     if let label = subview as? UILabel { 
      label.textColor = textColor 
     } else { 
      setSubviewLabelsToTextColor(textColor, view: subview) 
     } 
    } 
} 
+0

questa non è una soluzione alla mia domanda. Voglio cambiare lo stile del pulsante (font), non gli stili di titolo e messaggio – wplong11

+0

Che cos'è KVC ??? – wplong11

+0

Dai un'occhiata a questo http://stackoverflow.com/questions/26460706/uialertcontroller-custom-font-size-color btw KVC è la codifica valore-chiave https://developer.apple.com/library/ios/documentation/ Cacao/concettuale/KeyValueCoding/Articoli/Overview.html # // apple_ref/doc/uid/20001838-SW1 –

1

Ho la soluzione qui. Ho creato un AlertThemeConfigurator personalizzato che scorre ricorsivamente in tutte le sottoview alla ricerca di UILabels, quindi imposta su di esse il testo attribuito a tema per il titolo, il messaggio e diversi tipi di azioni. Sentiti libero di definire le stringhe attribuite in modo appropriato.

class AlertThemeConfigurator { 

    class func configureAlertViewController(alertController : UIAlertController) { 
     AlertLabelConfigurator.adjustLabels(inView: alertController.view, alertController: alertController) 
    } 

    class AlertLabelConfigurator { 

     class func adjustLabels(inView view : UIView, alertController : UIAlertController) { 
      for subview in view.subviews { 

       if subview is UILabel { 
        adjustLabel((subview as! UILabel), inAlertViewController : alertController) 
       } 

       adjustLabels(inView :subview, alertController : alertController) 
      } 
     } 

     class func adjustLabel(label : UILabel, inAlertViewController alertController : UIAlertController) { 
      if label.text == alertController.title { 
       label.attributedText = attributedTitle(label.text!) 
      } else if label.text == alertController.message { 
       label.attributedText = attributedBody(label.text!) 
      } 

      for action in alertController.actions { 
       if label.text == action.title { 
        switch action.style { 
        case .Default: 
         label.attributedText = attributedDefaultAction(action.title!) 
        case .Cancel: 
         label.attributedText = attributedCancelAction(action.title!) 
        case .Destructive: 
         label.attributedText = attributedDestructiveAction(action.title!) 
        } 
       } 
      } 
     } 

     class func attributedTitle(title : String) -> NSAttributedString { 
      let attributes = [NSFontAttributeName:UIFont(name: "Avenir-Medium", size: 20)!, NSForegroundColorAttributeName : UIColor.greenColor()] 
      return NSAttributedString(string: title, attributes: attributes) 
     } 

     class func attributedBody(title : String) -> NSAttributedString { 
      let attributes = [NSFontAttributeName:UIFont(name: "Avenir-Medium", size: 12)!, NSForegroundColorAttributeName : UIColor.orangeColor()] 
      return NSAttributedString(string: title, attributes: attributes) 
     } 

     class func attributedDefaultAction(title : String) -> NSAttributedString { 
      let attributes = [NSFontAttributeName:UIFont(name: "Avenir-Medium", size: 14)!, NSForegroundColorAttributeName : UIColor.yellowColor()] 
      return NSAttributedString(string: title, attributes: attributes) 
     } 

     class func attributedCancelAction(title : String) -> NSAttributedString { 
      let attributes = [NSFontAttributeName:UIFont(name: "Avenir-Medium", size: 14)!, NSForegroundColorAttributeName : UIColor.purpleColor()] 
      return NSAttributedString(string: title, attributes: attributes) 
     } 

     class func attributedDestructiveAction(title : String) -> NSAttributedString { 
      let attributes = [NSFontAttributeName:UIFont(name: "Avenir-Medium", size: 14)!, NSForegroundColorAttributeName : UIColor.redColor()] 
      return NSAttributedString(string: title, attributes: attributes) 
     } 
    } 
} 

di presentarlo chiamare

let alert = CustomAlertController(title: "Title", message:"Message" , preferredStyle: UIAlertControllerStyle.ActionSheet) 
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil)) 
presentViewController(alert, animated: true, completion: nil) 
AlertThemeConfigurator.configureAlertViewController(alert) 
+0

Penso che non sia consentito creare sottoclassi di UIAlertController in base alle linee guida di Apple. –

+0

Ho appena aggiornato la soluzione per non ereditare da UIAlertViewController :) Spero che questo aiuti – AntonTheDev

+0

@BhavukJain Ho appena aggiornato ancora una volta e ho creato una classe privata per eseguire il tema dell'etichetta, in modo che i metodi non siano esposti – AntonTheDev

1

Non è permesso a entrambi sottoclasse o il cambiamento di default cose di un UIAlertController. È necessario creare una visualizzazione personalizzata per questo.

Problemi correlati