UITableView with SearchView makes new cells overlap old ones on search - ios

Iam implementing a SearchView to filter the data in my UITableView. Iam able to search successfully, the only issue is when the UITableView data gets filtered, the old cells still exist and the filtered ones overlap them giving me a messy output. I have cleared the Table source as suggested by my answers on SO, but still not resolved the problem.
Here is what Iam trying to do:
FilterController
void searchFiler_TextChanged(object sender, UISearchBarTextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.SearchText))
{
ppTable.Source = null;
AppDelegate.filteredList = null;
ppTable.ReloadData();
filteredModelList = filter(dupes, e.SearchText);
mAdapter = new PeoplePlacesSource(filteredModelList, "");
ppTable.Source = mAdapter;
ppTable.ReloadData();
}
else
{
ppTable.Source = null;
mAdapter = new PeoplePlacesSource(dupes, "");
searchFiler.TextChanged += searchFiler_TextChanged;
mAdapter.TableRowSelected += mAdapter_TableRowSelected;
ppTable.Source = mAdapter;
ppTable.ReloadData();
}
}
PeoplePlacesSource
public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
{
cell = tableView.DequeueReusableCell("PeoplePlacesCell_Cell") as PeoplePlacesCell ?? PeoplePlacesCell.Create();
subList = userList.ElementAt(indexPath.Row);
cell.UpdatePeoplePlacesCell(subList);
return cell;
}
PeoplePlacesCell
internal void UpdatePeoplePlacesCell(System.Linq.IGrouping<string, Models.EmployeeModel> subList)
{
var yPosition =15;
var xPosition = 10;
var imgDefault = new UIImageView();
imgDefault.Frame = new CoreGraphics.CGRect(10, viewParent.Frame.Y, 60,60);
imgDefault.Image = UIImage.FromFile("ic_appicon.png");
CALayer profileImageCircle = imgDefault.Layer;
profileImageCircle.CornerRadius = 28;
profileImageCircle.BorderWidth = 2;
profileImageCircle.BorderColor = new CoreGraphics.CGColor(211, 34, 41);
profileImageCircle.MasksToBounds = true;
imgDefault.ClipsToBounds = true;
viewParent.AddSubview(imgDefault);
var labelUserName = new UILabel();
labelUserName.Frame = new CoreGraphics.CGRect(0, 0, viewContainer.Frame.Width, 30);
labelUserName.TextColor = UIColor.FromRGB(211, 34, 41);
labelUserName.Text = subList.Key ;
labelUserName.ClipsToBounds = true;
labelUserName.Font = UIFont.BoldSystemFontOfSize(17);
viewContainer.AddSubview(labelUserName);
var mList = subList.Take(5);
foreach (var employeeModel in mList)
{
var labelPlace = new UILabel();
labelPlace.Frame = new CoreGraphics.CGRect(0, yPosition, viewContainer.Frame.Width, 50);
if (employeeModel.Place.Contains(","))
{
labelPlace.Text = employeeModel.Place.Substring(0, employeeModel.Place.IndexOf(","));
}
else
{
labelPlace.Text = employeeModel.Place;
}
labelPlace.Font = UIFont.FromName(labelPlace.Font.Name, 12f);
labelUserName.SizeToFit();
labelPlace.ClipsToBounds = true;
viewContainer.AddSubview(labelPlace);
yPosition += 15;
}
}
How can I solve this? Any help is appreciated

Do you have the same problem after scroll? You cells are reused, but I don't see code for removing added subviews. Try to remove all subviews you added, before reusing cells.

Related

I'm having problems zooming into images that are in rows of an UITableView in Xamarin.iOS

I have a tableView inside a tabView, and my rows in the tableView contain images. I would like to zoom into the said images (I put them inside a scrollView and set the max/min zoom and I set ViewForZoomingInScrollView), but it seems I can't get the zoom to trigger because they are small images 50x56 or some other gesture/event is interfeiring. I use the same zoom code on another part of my app and it works perfectly. Has anyone come across the same or similar problem or knows a possible solution?
EDIT:
protected DocumentBaseCell()
: base(UITableViewCellStyle.Default, new NSString("TableCell"))
{
...
documentImage = new UIImageView();
documentImage.Image = UIImage.FromBundle("LaunchImage");
documentImage.ContentMode = UIViewContentMode.ScaleAspectFit;
documentImage.Layer.ZPosition = 0;
imageScrollView = new UIScrollView();
imageScrollView.ClipsToBounds = false;
imageScrollView.ContentSize = new CGSize(50, 56);
imageScrollView.MaximumZoomScale = 8f;
imageScrollView.MinimumZoomScale = 1f;
imageScrollView.Add(documentImage);
imageScrollView.ViewForZoomingInScrollView += (UIScrollView sv) =>
{
imageScrollView.ContentSize = new CGSize(documentImage.Frame.Width, documentImage.Frame.Height);
return documentImage;
};
imageScrollView.DidZoom += (object sender, EventArgs e) =>
{
//(sender as UIView).Layer.ZPosition = 2000;
};
imageScrollView.ZoomingEnded += (object sender, ZoomingEndedEventArgs e) =>
{
(sender as UIScrollView).SetZoomScale(0f, true);
(sender as UIView).Layer.ZPosition = 0;
this.Layer.ZPosition = 0;
};
ContentView.Add(imageScrollView);
...
}
And this is the UpdateCell method:
internal virtual void UpdateCell(DocumentModel doc, string sup, string
docType, string user, string date, UIImage image)
{
if (image != null)
{
this.documentImage.Image = image;
}
...
}
The Frame is set aswell:
public override void LayoutSubviews()
{
base.LayoutSubviews();
imageScrollView.Frame = new CGRect(0, 2, 50, 56);
documentImage.Frame = new CGRect(0, 0, 50, 56);
}
I think you should give a frame to imageScrollView and documentImage, I download the official tableView sample project and add your code there, it zooms well.
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
imageScrollView.Frame = new CGRect(ContentView.Bounds.Width - 233, 5, 133, 133);
headingLabel.Frame = new CGRect(5, 4, ContentView.Bounds.Width - 63, 25);
subheadingLabel.Frame = new CGRect(100, 18, 100, 20);
imageView.Frame = imageScrollView.Bounds;
}
I uploaded a sample project here and you can check it.

Print WebView with multiple pages in Xamarin UWP

I am trying to print web page in xamarin forms. I am using DependencyService to print webview, which I have implemented in android successfully.
For Windows UWP,
I referred to this link:
https://forums.xamarin.com/discussion/91163/problem-with-printing-webview-in-uwp-phone
The approach used in this is printing only the first page of the webpage.
Edit :
I created an interface IPrint providing only the html source to the function.
public interface IPrint
{
void PrintAsync(string htmlSource);
}
In PrintAsync function (in Windows UWP project),
async void IPrint.PrintAsync(string htmlSource)
{
ViewToPrint.NavigateToString(htmlSource);
ViewToPrint.LoadCompleted += ViewToPrint_LoadCompleteAsync;
}
When WebView is completely loaded,
private async void ViewToPrint_LoadCompleteAsync(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
if (PrintDoc != null)
{
printDoc.AddPages -= PrintDoc_AddPages;
printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
printDoc.Paginate -= PrintDoc_Paginate;
}
this.printDoc = new PrintDocument();
try
{
printDoc.AddPages += PrintDoc_AddPages;
printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
printDoc.Paginate += PrintDoc_Paginate;
bool showprint = await PrintManager.ShowPrintUIAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
PrintDoc = null;
GC.Collect();
}
To add pages in PrintDocument,
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(ViewToPrint);
printDoc.AddPagesComplete();
}
To implement multiple pages printing,
I referred this link : https://stackoverflow.com/a/17222629/6366591
I changed AddPages function to the following, but it doesn't seem to work for me.
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
rectangleList = GetWebPages(ViewToPrint, new Windows.Foundation.Size(100d, 150d));
foreach (Windows.UI.Xaml.Shapes.Rectangle rectangle in rectangleList)
{
printDoc.AddPage(rectangle);
}
printDoc.AddPagesComplete();
}
You can find GetWebPages() function here.
List<Windows.UI.Xaml.Shapes.Rectangle> GetWebPages(Windows.UI.Xaml.Controls.WebView webView, Windows.Foundation.Size page)
{
// ask the content its width
var _WidthString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" }).GetResults();
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// ask the content its height
var _HeightString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" }).GetResults();
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// how many pages will there be?
var _Scale = page.Width / _ContentWidth;
var _ScaledHeight = (_ContentHeight * _Scale);
var _PageCount = (double)_ScaledHeight / page.Height;
_PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);
// create the pages
var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
for (int i = 0; i < (int)_PageCount; i++)
{
var _TranslateY = -page.Height * i;
var _Page = new Windows.UI.Xaml.Shapes.Rectangle
{
Height = page.Height,
Width = page.Width,
Margin = new Windows.UI.Xaml.Thickness(5),
Tag = new Windows.UI.Xaml.Media.TranslateTransform { Y = _TranslateY },
};
_Page.Loaded += (s, e) =>
{
var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
var _Brush = GetWebViewBrush(webView);
_Brush.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
_Brush.AlignmentY = Windows.UI.Xaml.Media.AlignmentY.Top;
_Brush.Transform = _Rectangle.Tag as Windows.UI.Xaml.Media.TranslateTransform;
_Rectangle.Fill = _Brush;
};
_Pages.Add(_Page);
}
return _Pages;
}
WebViewBrush GetWebViewBrush(Windows.UI.Xaml.Controls.WebView webView)
{
// resize width to content
var _OriginalWidth = webView.Width;
var _WidthString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" }).GetResults();
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// resize height to content
var _OriginalHeight = webView.Height;
var _HeightString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" }).GetResults();
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// create brush
var _OriginalVisibilty = webView.Visibility;
webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
var _Brush = new WebViewBrush
{
SourceName = webView.Name,
Stretch = Windows.UI.Xaml.Media.Stretch.Uniform
};
_Brush.Redraw();
// reset, return
webView.Width = _OriginalWidth;
webView.Height = _OriginalHeight;
webView.Visibility = _OriginalVisibilty;
return _Brush;
}
#Jerry Nixon's method worked well on my side. Since his code sample was posted on that thread about five years ago. For current UWP APIs, I just done a little changes(e.g, webView.InvokeScriptAsync). I also saw that you call the webView.InvokeScriptAsync method in your code. That's good. But you call the GetResults() method, I did not suggest you call GetResults() method. Because invoking javascript code sometimes will take you a lot of time. You might get the exception A method was called at an unexpected time.
Then, I also noticed that your printing flow is a bit of a mess. Please read Print from your app to learn the standardized printing process.
You could check the official code sample Printing sample for details.
The following was the updated code of your code snippet:
async Task<List<Windows.UI.Xaml.Shapes.Rectangle>> GetWebPages(Windows.UI.Xaml.Controls.WebView webView, Windows.Foundation.Size page)
{
// ask the content its width
var _WidthString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" });
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// ask the content its height
var _HeightString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" });
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// how many pages will there be?
var _Scale = page.Width / _ContentWidth;
var _ScaledHeight = (_ContentHeight * _Scale);
var _PageCount = (double)_ScaledHeight / page.Height;
_PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);
// create the pages
var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
for (int i = 0; i < (int)_PageCount; i++)
{
var _TranslateY = -page.Height * i;
var _Page = new Windows.UI.Xaml.Shapes.Rectangle
{
Height = page.Height,
Width = page.Width,
Margin = new Windows.UI.Xaml.Thickness(5),
Tag = new Windows.UI.Xaml.Media.TranslateTransform { Y = _TranslateY },
};
_Page.Loaded +=async (s, e) =>
{
var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
var _Brush = await GetWebViewBrush(webView);
_Brush.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
_Brush.AlignmentY = Windows.UI.Xaml.Media.AlignmentY.Top;
_Brush.Transform = _Rectangle.Tag as Windows.UI.Xaml.Media.TranslateTransform;
_Rectangle.Fill = _Brush;
};
_Pages.Add(_Page);
}
return _Pages;
}
async Task<WebViewBrush> GetWebViewBrush(Windows.UI.Xaml.Controls.WebView webView)
{
// resize width to content
var _OriginalWidth = webView.Width;
var _WidthString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" });
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// resize height to content
var _OriginalHeight = webView.Height;
var _HeightString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" });
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// create brush
var _OriginalVisibilty = webView.Visibility;
webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
var _Brush = new WebViewBrush
{
SourceName = webView.Name,
Stretch = Windows.UI.Xaml.Media.Stretch.Uniform
};
_Brush.Redraw();
// reset, return
webView.Width = _OriginalWidth;
webView.Height = _OriginalHeight;
webView.Visibility = _OriginalVisibilty;
return _Brush;
}
I used the Printing sample and put my above updated code in it and do some relevant changes, then I could print all web pages successfully.

How to add watermark to aspose pdf and word that contain table

I generate a Aspose.Generate.Pdf file and then add a Aspose.Pdf.Generator.Tableto it by following method. but when I add watermark to this pdf file, it covers by created table:
public static BasketResult<string> ExportDataTableToPdf(DataTable inputDataTable, string CaptionFilename)
{
List<DataColumn> listDataColumns = GetDataColumns(inputDataTable, CaptionFilename);
BasketResult<string> returnResult = new BasketResult<string>();
String rtnPathFile = String.Empty;
int rowCount = inputDataTable.Rows.Count;
if (rowCount <= 1000)
{
try
{
string dataDir = Settings.TempPath;
if (!Directory.Exists(dataDir))
Directory.CreateDirectory(dataDir);
Pdf pdfConv = new Pdf();
pdfConv.IsRightToLeft = true;
Aspose.Pdf.Generator.Section mainSection = pdfConv.Sections.Add();
mainSection.TextInfo.IsRightToLeft = true;
mainSection.IsLandscape = true;
mainSection.TextInfo.Alignment = AlignmentType.Right;
// header definition begin
Aspose.Pdf.Generator.HeaderFooter header = new Aspose.Pdf.Generator.HeaderFooter(mainSection);
mainSection.EvenHeader = header;
mainSection.OddHeader = header;
header.Margin.Top = 50;
Aspose.Pdf.Generator.Table headerTable = new Aspose.Pdf.Generator.Table();
header.Paragraphs.Add(headerTable);
headerTable.DefaultCellBorder = new BorderInfo((int)BorderSide.All, 0.1F);
headerTable.Alignment = AlignmentType.Right;
headerTable.DefaultColumnWidth = "80";
headerTable.FixedHeight = 30;
Aspose.Pdf.Generator.Row headerRow = headerTable.Rows.Add();
headerRow.BackgroundColor = new Aspose.Pdf.Generator.Color("#D3DFEE");
int index = 0;
listDataColumns.Reverse();
foreach (DataColumn column in listDataColumns)
{
string cellText = column.Caption;
headerRow.Cells.Add(cellText);
headerRow.Cells[index].DefaultCellTextInfo.FontName = "Tahoma";
headerRow.Cells[index].DefaultCellTextInfo.IsRightToLeft = true;
headerRow.Cells[index].VerticalAlignment = VerticalAlignmentType.Center;
headerRow.Cells[index++].Alignment = AlignmentType.Center;
}
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Aspose.Words.Tables.Table wordTable = ImportTableFromDataTable(builder, inputDataTable,
CaptionFilename, true);
string columnWidths = "";
for (int j = 0; j < wordTable.FirstRow.Count; j++)
{
columnWidths = columnWidths + "80 ";
}
Aspose.Pdf.Generator.Table table = new Aspose.Pdf.Generator.Table();
mainSection.Paragraphs.Add(table);
table.ColumnWidths = columnWidths;
table.DefaultCellBorder = new BorderInfo((int)BorderSide.All, 0.1F);
table.Alignment = AlignmentType.Right;
//fill table
for (int i = 1; i < wordTable.Rows.Count; i++)
{
Aspose.Pdf.Generator.Row row = table.Rows.Add();
row.BackgroundColor = i % 2 == 0
? new Aspose.Pdf.Generator.Color("#D3DFEE")
: new Aspose.Pdf.Generator.Color("#FFFFFF");
var wordTableRow = wordTable.Rows[i];
//fill columns from end to begin because table is left to right
for (int c = wordTable.FirstRow.Count - 1; c >= 0; c--)
{
var cellValue = wordTableRow.ChildNodes[c];
string cellText = cellValue.GetText();
row.Cells.Add(cellText);
}
//set style to every cell
for (int c = 0; c < wordTable.FirstRow.Count; c++)
{
row.Cells[c].DefaultCellTextInfo.FontName = "Tahoma";
row.Cells[c].DefaultCellTextInfo.IsRightToLeft = true;
row.Cells[c].VerticalAlignment = VerticalAlignmentType.Center;
row.Cells[c].Alignment = AlignmentType.Center;
}
}
pdfConv.SetUnicode();
rtnPathFile = Helper.GetTempFile() + ".pdf";
string fileName = Helper.GetFileNameFromFilePath(rtnPathFile);
pdfConv = AddPdfWatermark(pdfConv);
pdfConv.Save(dataDir + fileName);
returnResult.Result.Add(rtnPathFile);
returnResult.IsSuccess = true;
}
catch (Exception ex)
{
rtnPathFile = String.Empty;
returnResult.IsSuccess = false;
returnResult.Result.Add(rtnPathFile);
returnResult.persianErrorMessages.Add(Messages.Err_InvalidFilePath);
}
}
else
{
returnResult.IsSuccess = false;
returnResult.Result.Add(rtnPathFile);
returnResult.persianErrorMessages.Add(Messages.Err_CreateFile);
}
return returnResult;
}
and AddPdfWatermerk method is :
private static Pdf AddPdfWatermark(Aspose.Pdf.Generator.Pdf pdfConv)
{
try
{
// Create FloatingBox with x as width and y as height
Aspose.Pdf.Generator.FloatingBox background = new Aspose.Pdf.Generator.FloatingBox(); // width, height
Aspose.Pdf.Generator.Image backImage = new Aspose.Pdf.Generator.Image();
string path = HttpContext.Current.Server.MapPath("~/images/PrivateExcelBackGround.png");
byte[] bgBuffer = File.ReadAllBytes(path);
MemoryStream streamBack = new MemoryStream(bgBuffer, false);
backImage.ImageInfo.ImageStream = streamBack;
background.Paragraphs.Add(backImage);
background.ZIndex = 1000;
pdfConv.Watermarks.Add(background);
pdfConv.IsWatermarkOnTop = false;
return pdfConv;
}
catch
{
return pdfConv;
}
}
I tried stamp instead of watermark, but table masks it too.
in aspose.words.document file I have a problem too, in word file with mentioned table,watermark added correctly but when a colored alternate table rows, watermark covered by colorful rows.
You are using an out-dated version of Aspose.PDF API. Kindly upgrade to Aspose.PDF for .NET 18.1, which includes more features and bug fixes. You can add an image stamp by using below code snippet in your environment.
// Open document
Document pdfDocument = new Document(dataDir+ "AddImageStamp.pdf");
// Create image stamp
ImageStamp imageStamp = new ImageStamp(dataDir + "aspose-logo.jpg");
imageStamp.Background = true;
imageStamp.XIndent = 100;
imageStamp.YIndent = 100;
imageStamp.Height = 300;
imageStamp.Width = 300;
imageStamp.Rotate = Rotation.on270;
imageStamp.Opacity = 0.5;
// Add stamp to particular page
pdfDocument.Pages[1].AddStamp(imageStamp);
dataDir = dataDir + "AddImageStamp_out.pdf";
// Save output document
pdfDocument.Save(dataDir);
ImageStamp class provides the properties necessary for creating an image-based stamp, such as height, width, opacity etc. You may visit Adding stamp in a PDF file for further information on this topic. In case you notice any problem with the file generated by using this code, please get back to us with source and generated file so that we may proceed to help you out.
I work with Aspose as Developer Evangelist.

How do I remove gesture recogniser from a label in a UITableViewCell?

I've bottom toolbar in my ViewController and a TableView above it. The toolbar has a date label in the middle, and next and previous buttons on the left and right. based on the selected date tableview content changes..
Now TableViewCell contains a UILabel. I want to add Gesture to the label only if the selected day is today.
So I wrote in my cell update method
UITapGestureRecognizer gesture = new UITapGestureRecognizer();
gesture.AddTarget(() => HandleValueLabelClick());
if (source.parentController.selectedDateTime.Day == DateTime.Now.Day)
{
AddEditAction();
ValueLabel.AddGestureRecognizer(gesture);
}
else
{
ValueLabel.RemoveGestureRecognizer(gesture);
}
But the gesture remove if the selected date is not today, is not working. Any help is appreciated..
Edit:
public partial class ProgramCalendarCell : UITableViewCell
{
NSIndexPath indexPath;
ProgramVitalsCalendarTableSource source;
ProgramVital vital;
ProgramVitalCalendar calendar;
public ProgramCalendarCell (IntPtr handle) : base (handle)
{
}
public void UpdateCell(ProgramVital vital, ProgramVitalCalendar calendar, NSIndexPath indexPath, ProgramVitalsCalendarTableSource source)
{
this.source = source;
this.indexPath = indexPath;
this.vital = vital;
this.calendar = calendar;
InitVitalName();
InitVitalValue();
NewValueTextField.Hidden = true;
ValueLabel.Hidden = false;
UIView separatorLine = new UIView(new CoreGraphics.CGRect(0, 44, 1200f, 0.5f));
separatorLine.BackgroundColor = AZConstants.SeparatorColor;
ContentView.AddSubview(separatorLine);
UITapGestureRecognizer gesture = new UITapGestureRecognizer();
gesture.AddTarget(() => HandleValueLabelClick());
if (source.parentController.selectedDateTime.Day == DateTime.Now.Day)
{
AddEditAction();
ValueLabel.AddGestureRecognizer(gesture);
}
else
{
ValueLabel.RemoveGestureRecognizer(gesture);
}
}
void InitVitalName()
{
string name = vital.vitalName;
if (!String.IsNullOrEmpty(vital.unitName))
name += " (" + System.Net.WebUtility.HtmlDecode(vital.unitName) + ")";
VitalNameLabel.Text = name;
}
void InitVitalValue()
{
string value = "";
string color = "";
if (calendar != null)
{
value = calendar.values[0].value;
color = calendar.values[0].color;
}
UIHelper.SetVitalValueTileBackGround(ValueLabel, value, color);
}
void HandleValueLabelClick()
{
ValueLabel.Hidden = true;
NewValueTextField.Hidden = false;
NewValueTextField.BecomeFirstResponder();
}
void AddEditAction()
{
ValueLabel.UserInteractionEnabled = true;
NewValueTextField.ShouldReturn = (textField) =>
{
textField.ResignFirstResponder();
ValueLabel.Hidden = false;
NewValueTextField.Hidden = true;
Console.WriteLine("Row: " + indexPath.Row);
return true;
};
UIToolbar toolbar = new UIToolbar(new RectangleF(0.0f, 0.0f, (float)UIScreen.MainScreen.Bounds.Size.Width, 44.0f));
toolbar.BarTintColor = AZConstants.PrimaryColor;
toolbar.TintColor = UIColor.White;
toolbar.Items = new UIBarButtonItem[]{
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
new UIBarButtonItem(UIBarButtonSystemItem.Done, delegate {
Console.WriteLine("Row: " + indexPath.Row);
SaveReading();
NewValueTextField.ResignFirstResponder();
})
};
toolbar.BarTintColor = AZConstants.PrimaryColor;
toolbar.TintColor = UIColor.White;
toolbar.Translucent = true;
toolbar.SizeToFit();
NewValueTextField.InputAccessoryView = toolbar;
int vId = Int32.Parse(vital.vitalId);
if (vId == 20 || vId == 5 || vId == 496)
NewValueTextField.KeyboardType = UIKeyboardType.DecimalPad;
else
NewValueTextField.KeyboardType = UIKeyboardType.NumberPad;
}
async void SaveReading()
{
var hud = UIHelper.GetProgressHud(source.parentController.View, "");
hud.Show(animated: true);
Status status = await VitalHelper.postVitalValue(Constants.__IOS__, vital, NewValueTextField.Text, 0,
DateTime.Now.ToString("MM/dd/yyyy"), DateTime.Now.ToString("hh:mm tt"), "");
if (status.status)
{
source.parentController.FetchAndDisplayVitalValues();
}
else
{
new UIAlertView("Error", status.message, null, "OK", null).Show();
}
hud.Hide(animated: true, delay: 0);
}
}
It doesn't work 'cause you are removing a newly created gesture, not the gesture it already may have.
You must retrive the gestures array with ValueLabel.gestureRecognizers then remove each one with a for loop.

Change colors in devexpress charts

I am drawing a pie chart using Devexpress in my MVC project.
While doing it by default my chart generated with three colors, as below
but my client is not satisfied, with the colors of it and wanted me to change them which match with our application background, so please help me, how to do this.
Thanks in advance.
Here is my code.
settings.Name = "chart";
settings.Width = 600;
settings.Height = 250;
settings.BorderOptions.Visible = false;
Series series1 = new Series("Type", DevExpress.XtraCharts.ViewType.Pie3D);
settings.Series.Add(series1);
series1.ArgumentScaleType = ScaleType.Qualitative;
series1.ArgumentDataMember = "ClassName";
series1.ValueScaleType = ScaleType.Numerical;
series1.ValueDataMembers.AddRange(new string[] { "PercentageValues" });
series1.LegendPointOptions.PointView = PointView.ArgumentAndValues;
series1.LegendPointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
series1.LegendPointOptions.ValueNumericOptions.Precision = 0;
series1.Label.ResolveOverlappingMode = ResolveOverlappingMode.Default;
series1.Label.Visible = false;
Please refer the following code. I have successfully implemented the same for giving custom color for rangebar. I guess it will work for your case also
settings.CustomDrawSeriesPoint = (s, ev) =>
{
BarDrawOptions drawOptions = ev.SeriesDrawOptions as BarDrawOptions;
if (drawOptions == null)
return;
Color colorInTarget = Color.Blue;
double x = ev.SeriesPoint.Values[0];
double y = ev.SeriesPoint.Values[1];
if (x == 0)
{ //Do starting
colorInTarget = Color.FromArgb(159,125, 189);
}
else{
//Red - price Increase
// Green price Decrease
if (y > previousYValue)
{
colorInTarget = Color.Red; ;
}
else
{
colorInTarget = Color.Green;
}
}
previousYValue = y;
drawOptions.Color = colorInTarget;
drawOptions.FillStyle.FillMode = FillMode.Solid;
drawOptions.Border.Color = Color.Transparent;
};
you can set the theme and palette properties of the chart control. follow the links below to devexpress documentation. although the examples refers to winform application they are still avaliable in asp.net mvc controls.
http://documentation.devexpress.com/#WindowsForms/CustomDocument7433
http://documentation.devexpress.com/#WindowsForms/CustomDocument5538
// Define the chart's appearance and palette.
barChart.AppearanceName = "Dark";
barChart.PaletteName = "Opulent";
private List<StudentClass.ChartsPointsSummary> GetStudentSummaryResults()
{
var StudentId = Convert.ToInt32(Request.Params["StudentID"]);
var StudentDetailsP = CtxSM.SMISGet_StudentAttendanceDetailsByStudentId(StudentId, SessionDataManager.SessionData.LoginUserId, SessionDataManager.SessionData.AcademicYearID, SessionDataManager.SessionData.BusinessUnitId, ref outError).ToList();
var Presents = StudentDetailsP.Select(p => new { p.Months, p.Presents});
var CountsP = StudentDetailsP.Count();
List<StudentClass.ChartsPointsSummary> MT = new List<StudentClass.ChartsPointsSummary>();
foreach (var ab in Presents)
{
MT.Add(new StudentClass.ChartsPointsSummary { PresentSummaryX = ab.Months, PresentSummaryY = Convert.ToInt32(ab.Presents) });
}
var StudentDetailsA = CtxSM.SMISGet_StudentAttendanceDetailsByStudentId(StudentId, SessionDataManager.SessionData.LoginUserId, SessionDataManager.SessionData.AcademicYearID, SessionDataManager.SessionData.BusinessUnitId, ref outError).ToList();
var Absents = StudentDetailsP.Select(p => new { p.Months, p.Absents });
var CountsA = StudentDetailsA.Count();
foreach (var ab in Absents)
{
MT.Add(new StudentClass.ChartsPointsSummary { AbsentSummaryX = ab.Months, AbsentSummaryY = Convert.ToInt32(ab.Absents) });
}
var StudentDetailsL = CtxSM.SMISGet_StudentAttendanceDetailsByStudentId(StudentId, SessionDataManager.SessionData.LoginUserId, SessionDataManager.SessionData.AcademicYearID, SessionDataManager.SessionData.BusinessUnitId, ref outError).ToList();
var CountL = StudentDetailsL.Count();
var Leaves = StudentDetailsP.Select(p => new { p.Months, p.Leaves });
foreach (var ab in Leaves)
{
MT.Add(new StudentClass.ChartsPointsSummary { LeaveSummaryX = ab.Months, LeaveSummaryY = Convert.ToInt32(ab.Leaves) });
}
return MT;
}
#Html.DevExpress().Chart(settings =>
{
settings.Name = "SummaryDetailsById";
settings.Width = 1032;
settings.Height = 250;
Series chartSeries = new Series("Presents", DevExpress.XtraCharts.ViewType.Bar);
chartSeries.ArgumentDataMember = "PresentSummaryX";
chartSeries.ValueDataMembers[0] = "PresentSummaryY";
settings.Series.Add(chartSeries);
Series chartSeries2 = new Series("Absents", DevExpress.XtraCharts.ViewType.Bar);
chartSeries2.ArgumentDataMember = "AbsentSummaryX";
chartSeries2.ValueDataMembers[0] = "AbsentSummaryY";
settings.Series.Add(chartSeries2);
Series chartSeries3 = new Series("Leaves", DevExpress.XtraCharts.ViewType.Bar);
chartSeries3.ArgumentDataMember = "LeaveSummaryX";
chartSeries3.ValueDataMembers[0] = "LeaveSummaryY";
settings.Series.Add(chartSeries3);
settings.CrosshairEnabled = DefaultBoolean.Default;
settings.BackColor = System.Drawing.Color.Transparent;
settings.BorderOptions.Visibility = DefaultBoolean.True;
settings.Titles.Add(new ChartTitle()
{
Text = "Student Attendance Summary"
});
XYDiagram diagram = ((XYDiagram)settings.Diagram);
diagram.AxisX.Label.Angle = -30;
diagram.AxisY.Interlaced = true;
}).Bind(Model).GetHtml()

Resources