我尝试从一个类引用扩展方法但是收到以下错误:"错误:UIColor不包含' FromHex'"的定义。我的设置如下。我在错误源自的行的开头添加了一个箭头(箭头不是我的代码的一部分)。
我有一个Alert类:
using System;
using UIKit;
using System.Linq;
using MyApp.iOS;
[assembly: Xamarin.Forms.Dependency(typeof(MyApp.iOS.Alert))]
namespace MyApp.iOS {
public class Alert : IAlert {
public void ShowAlert(string title, string message, string button) {
ShowAlert(title, message, button, null);
}
public void ShowAlert(string title, string message, string button, string hexColor) {
var okAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
okAlertController.AddAction(UIAlertAction.Create(button, UIAlertActionStyle.Default, null));
if (hexColor != null) {
UIView firstSubView = okAlertController.View.Subviews.First();
UIView alertContentView = firstSubView.Subviews.First();
foreach (UIView subSubView in alertContentView.Subviews) {
--> subSubView.BackgroundColor = UIColor.FromHex(hexColor); // This line is where I'm getting the error
}
okAlertController.View.TintColor = UIColor.Black;
}
var window = UIApplication.SharedApplication.KeyWindow;
var viewController = window.RootViewController;
while (viewController.PresentedViewController != null) viewController = viewController.PresentedViewController;
var navigationController = viewController as UINavigationController;
if (navigationController != null) viewController = navigationController.ViewControllers.Last();
viewController.PresentViewController(okAlertController, true, null);
}
}
}
我有一个UIColorExtensions类:
using System;
using System.Globalization;
using UIKit;
namespace MyApp.iOS {
public static class UIColorExtensions {
public static UIColor FromHex(this UIColor color, string hex) {
float a = 255, r = 0, g = 0, b = 0;
if (hex.StartsWith("#")) {
string hexColor = hex.Substring(1);
if (hexColor.Length == 8) {
float.TryParse(hexColor.Substring(0, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out a);
hexColor = hexColor.Substring(2, 6);
}
if (hexColor.Length == 6) {
float.TryParse(hexColor.Substring(2, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out r);
float.TryParse(hexColor.Substring(4, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out g);
float.TryParse(hexColor.Substring(6, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out b);
}
return UIColor.FromRGBA(r, g, b, a);
}
return null;
}
}
}
我无法弄清楚我可能做错了什么。
这是我迄今为止所做的尝试:
答案 0 :(得分:1)
问题是UIColor
不是类的实例,因此必须执行UIColor.Red.FromHex(hex)
之类的操作或修改扩展方法以便以另一种方式处理它。