Xamarin-ios小部件无法加载

时间:2017-12-15 21:51:17

标签: c# ios xamarin xamarin.ios tableview

在我的小部件中,我有tableview和5行的单元格。我正在获取数据并尝试初始化为Uilabels。 我正在尝试编写将数据初始化为单元格的数据源。 我没有任何构建错误,但它没有调用GetCell方法,我打破了它但没有发生任何事情。

同样在小部件中,文字“无法加载数据”

这是我的数据源代码

TodayViewController.cs

using System;
using System.Collections.Generic;
using NotificationCenter;
using Foundation;
using UIKit;
using CryptoCurrencyPCL.POCO;
using CryptoCurrencyPCL.Middleware;
using System.Linq;

namespace CryptoTodayWidget
{
    public partial class TodayViewController : UIViewController, INCWidgetProviding,IUITableViewDataSource,IUITableViewDelegate
    {

        const string ReuseId = "currencyCellReuseId";
        List<CoinsPrices> _coins;
        protected TodayViewController(IntPtr handle) : base(handle)
        {
            // Note: this .ctor should not contain any initialization logic.
        }

        public override void DidReceiveMemoryWarning()
        {
            // Releases the view if it doesn't have a superview.
            base.DidReceiveMemoryWarning();

            // Release any cached data, images, etc that aren't in use.
        }

        public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            var cell = tableView.DequeueReusableCell(ReuseId, indexPath) as WidgetCell;
            GetData();
            var item = _coins[indexPath.Row];

            cell.InitData(item);

            return cell;
        }

        public nint RowsInSection(UITableView tableView, nint section)
        {
            return _coins?.Count ?? 0;
        }

        [Export("tableView:heightForRowAtIndexPath:")]
        public nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
        {
            return 50;
        }

        [Export("numberOfSectionsInTableView:")]
        public nint NumberOfSections(UITableView tableView)
        {
            return 1;
        }

        public async void GetData()
        {
            var symbols = await DatabaseManager.Instance.GetRecentCoinsAsync(5);

            var webClient = CryptoCurrencyPCL.Services.CryptoWebClient.Instance;


            List<string> coinSymbols = new List<string>();

            foreach (var item in symbols)
            {
                coinSymbols.Add(item.symbol);
            }


            _coins = await webClient.GetCoinsWithDetailsAsync(coinSymbols);
        }


        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            tableView.DataSource = this;
            tableView.Delegate = this;
            tableView.ReloadData();
            PreferredContentSize = new CoreGraphics.CGSize(320, _coins.Count * 50);
            // Do any additional setup after loading the view.
        }

        [Export("widgetPerformUpdateWithCompletionHandler:")]
        public void WidgetPerformUpdate(Action<NCUpdateResult> completionHandler)
        {
            // Perform any setup necessary in order to update the view.

            // If an error is encoutered, use NCUpdateResultFailed
            // If there's no update required, use NCUpdateResultNoData
            // If there's an update, use NCUpdateResultNewData

            completionHandler(NCUpdateResult.NewData);

        }
    }
}

这是我的 Widgetcell.cs

using System;
using CryptoCurrencyPCL.POCO;
using Foundation;
using UIKit;

namespace CryptoTodayWidget
{
    public partial class WidgetCell : UITableViewCell
    {


        public WidgetCell (IntPtr handle) : base (handle)
        {
        }

        public void InitData(CoinsPrices coin){

            coinNameLbl.Text = coin.Coin.Name;
            coinPriceLbl.Text = coin.Detail.PRICE.ToString();
            percentLbl.Text = coin.Detail.CHANGEPCT24HOUR.ToString();

            if (coin.Detail.CHANGEPCT24HOUR < 0)
            {
                percentHolderView.BackgroundColor = Theme.DownColor;
            }

            else if (coin.Detail.CHANGE24HOUR > 0)
            {
                percentHolderView.BackgroundColor = Theme.UpColor;
            }
            else
            {
                percentHolderView.BackgroundColor = Theme.DownColor;
            }
        }

    }
}

1 个答案:

答案 0 :(得分:1)

这是因为您没有使用import csv import numpy as np ''' DEFINING MAIN CONTROL''' def main(): no_of_files # = number_of_files() a = Calculate_RMSE_Assess_Models() a.no_of_files() # = no_of_files a.pathlist() a.out_path() a.open_read_write_files() ''' DEFINING CLASS OF ALL ''' class Calculate_RMSE_Assess_Models: def __init__(self, no_of_files): self.no_of_files = no_of_files def number_of_files(): numfiles = input("Enter the number of files to iterate through: ") numfilesnumber = int(numfiles) return numfilesnumber no_of_files = number_of_files() def pathlist(self): filepathlist = [] while self.no_of_files > 0: #self.number_of_files path = input("Enter the filepath of the input file: ") filepathlist.append(path) no_of_files = no_of_files - 1 return filepathlist list_filepath = pathlist(no_of_files) def out_path(): path = input("Enter the file path of output path: ") return path file_out_path = outpath() def open_read_write_files(): with open('{d[0]}'.format(d=list_filepath), 'r') as csvinput, open('{d[1]}'.format(d=list_filepath), 'r') as csvinput2, open('d{[2]}'.format(d=list_filepath), 'r') as csvinput3, open('{d}'.format(d=file_out_path), 'w') as csvoutput: reader, reader2, reader3 = csv.reader(csvinput, csvinput2, csvinput3) #1: Decision Forest, 2: Boosted Decision Tree, 3: ANN writer = csv.DictWriter(csvoutput, lineterminator='\n', fieldnames = ['oldRMSE', 'Decision Forest Regression RMSE', 'Boosted Decision Tree Regression RMSE', 'Neural Network Regression RMSE', 'Old Accurate Predictions', 'Old Inaccurate Predictions', 'Decision Forest Accurate Predictions', 'Decision Forest Inaccurate Predictions', 'Boosted Decision Tree Accurate Predictions', 'Boosted Decision Tree Inaccurate Predictions', 'Neural Network Accurate Predictions', 'Neural Network Inaccurate Predictions']) ####################################### #For Decision Forest Predictions headerline = next(reader) emptyl=[] for row in reader: emptyl.append(row) #Calculate RMSE DecFSqResidSum = 0 for row in emptyl: for cell in row: if cell == row[-3]: DecFSqResidSum = float(cell) + DecFSqResidSum DecFSqResidAvg = DecFSqResidSum / len(emptyl) DecForest_RMSE = np.sqrt(DecFSqResidAvg) #Constructing No. of Correct/Incorrect Predictions DecisionForest_Accurate = 0 DecisionForest_Inaccurate = 0 Old_Accurate = 0 Old_Inaccurate = 0 for row in emptyl: for cell in row: if cell == row[-2] and 'Accurate' in cell: Old_Accurate += 1 else: Old_Inaccurate += 1 if cell == row[-1] and 'Accurate' in cell: DecisionForest_Accurate += 1 else: DecisionForest_Inaccurate += 1 ###################################### #For Boosted Decision Tree headerline2 = next(reader2) emptyl2=[] #make new csv file(list) from csv reader for row in reader2: emptyl2.append(row) #Calculate RMSE OldSqResidSum = 0 BoostDTSqResidSum = 0 for row in emptyl2: #make Sum of Squared Residuals for cell in row: if cell == row[-4]: OldSqResidSum = float(cell) + OldSqResidSum if cell == row[-3]: BoostDTSqResidSum = float(cell) + BoostDTSqResidSum OldSqResidAvg = OldSqResidSum / len(emptyl2) #divide by N to get average BoostDTResidAvg = BoostDTSqResidSum / len(emptyl2) oldRMSE = np.sqrt(OldSqResidAvg) #calculate RMSE of ESTARRTIME & Boosted Decision Tree BoostedDecTree_RMSE = np.sqrt(BoostDTResidAvg) #Constructing Correct/Incorrect Predictions BoostedDT_Accurate = 0 BoostedDT_Inaccurate = 0 for row in emptyl2: if cell == row[-1] and 'Accurate' in cell: BoostedDT_Accurate += 1 else: BoostedDT_Inaccurate += 1 ###################################### #For Artificial Neural Network (ANN) Predictions headerline3 = next(reader3) emptyl3=[] for row in reader3: emptyl3.append(row) #Calculate RMSE ANNSqResidSum = 0 for row in emptyl3: for cell in row: if cell == row[-3]: ANNSqResidSum = float(cell) + ANNSqResidSum ANNSqResidAvg = ANNSqResidSum / len(emptyl3) ANN_RMSE = np.sqrt(ANNSqResidAvg) #Constructing Correct/Incorrect Predictions ANN_Accurate = 0 ANN_Inaccurate = 0 for row in emptyl3: for cell in row: if cell == row[-1] and 'Accurate' in cell: ANN_Accurate += 1 else: ANN_Inaccurate += 1 #Compile the Error Measures finalcsv = [] finalcsv.append(oldRMSE) finalcsv.append(DecForest_RMSE) finalcsv.append(BoostedDecTree_RMSE) finalcsv.append(ANN_RMSE) finalcsv.append(Old_Accurate) finalcsv.append(Old_Inaccurate) finalcsv.append(DecisionForest_Accurate) finalcsv.append(DecisionForest_Inaccurate) finalcsv.append(BoostedDT_Accurate) finalcsv.append(BoostedDT_Inaccurate) finalcsv.append(ANN_Accurate) finalcsv.append(ANN_Inaccurate) #Write the Final Comparison file writer.writeheader() writer.writerows({'oldRMSE': row[0], 'Decision Forest Regression RMSE': row[1], 'Boosted Decision Tree Regression RMSE': row[2], 'Neural Network Regression RMSE': row[3], 'Old Accurate Predictions': row[4], 'Old Inaccurate Predictions': row[5], 'Decision Forest Accurate Predictions': row[6], 'Decision Forest Inaccurate Predictions': row[7], 'Boosted Decision Tree Accurate Predictions': row[8], 'Boosted Decision Tree Inaccurate Predictions': row[9], 'Neural Network Accurate Predictions': row[10], 'Neural Network Inaccurate Predictions': row[11]} for row in np.nditer(finalcsv)) main() 属性作为委托方法。

在Xamarin中使用GetCell时,它无法在iOS中找到绑定方法。

修改如下

Export

但是,我建议您采用正式方式完成这项工作。

在Xamarin.iOS中,我们经常使用[Export("tableView:cellForRowAtIndexPath:")] public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { } Strong Delegates在iOS中实现Weak Delegates

强代表

delegate protocol

弱代表

tableView.DataSource = new MyDelegate();
tableView.Delegate = new MyDataSource();

class MyDelegate: UITableViewDelegate
{
    public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
    {
        return 10;
    }
}

class MyDataSource: UITableViewDataSource
{
    public override nint RowsInSection(UITableView tableView, nint section)
    {

    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {

    }
}

请参阅Strong Delegates vs. Weak Delegates

相关问题