I need to create an action button with a image and text. below image provide
an example.
![1]: https://i.stack.imgur.com/KEuHn.png
i have created a method like
public UIContextualAction ContextualFlagAction(int row)
{
var action = UIContextualAction.FromContextualActionStyle(UIContextualActionStyle.Normal, "Flag", Handler);
(contextualAction, view, handler) =>
{
Console.WriteLine("Hello World!");
handler(false);
});
action.Image = UIImage.FromFile(ResourceIdentifiers.DocumentIcon);
return action;
}
but this is not what i need to do.
how can i customize this action as the image in the above.
Maybe your problem showed is the image result,your code have set action.image
If you have a image that contains picture and label , picture is up,label is down,there will be you want.
public UIContextualAction ContextualFlagAction(int row)
{
var action = UIContextualAction.FromContextualActionStyle(UIContextualActionStyle.Normal, "Flag", Handler);
(contextualAction, view, handler) =>
{
Console.WriteLine("Hello World!");
handler(false);
});
action.Image = UIImage.FromFile(ResourceIdentifiers.DocumentIcon);
//this is your setted image
return action;
}
More info:
You can custom a TableViewCell in Xamarin.ios.
Write the following method in UITableViewCell, Rewrite DidTransitionToState method in viewcell, you can replace the action with button
private UITableView tableViewThis;
public TableViewCellClass(UITableView tableView)
{
this.tableViewThis = tableView;
}
public override void DidTransitionToState(UITableViewCellState mask)
{
base.DidTransitionToState(mask);
if ((mask & UITableViewCellState.ShowingDeleteConfirmationMask) == UITableViewCellState.ShowingDeleteConfirmationMask)
{
foreach (UIView subview in tableViewThis.Subviews)
{
if (subview.Class.Equals("UIContextualAction"))
//Delete the delete button of the system
tableViewThis.WillRemoveSubview(subview);
subview.BackgroundColor = UIColor.Clear;
UIButton editBtn = new UIButton(UIButtonType.Custom);
editBtn.Frame = new CGRect(10, 4, 50, 65);
editBtn.SetBackgroundImage(UIImage.FromFile("1.png"), UIControlState.Normal);
editBtn.AdjustsImageWhenHighlighted = false;
editBtn.TouchUpInside += (sender, e) =>
{
//do something you need
};
subview.AddSubview(editBtn);
}
}
}
UIButton can set both Title and Image. UIButton has two properties:
titleEdgeInsets(top,left,bottom,right)
and imageEdgeInsets(top,left,bottom,right).
By setting these two, you can implement the style you need.
Related
I am testing a gtk4 widget which is GtkDropTarget. I plan on setting an image which is dragged to the window as the image of the window itself. But errors come up as soon as I drag an image file. To be clear, this is the code in vala:
int main (string[] args) {
var app = new App();
return app.run(args);
}
public class App : Gtk.Application {
public App () {
Object (
application_id: "com.github.ea",
flags: ApplicationFlags.FLAGS_NONE
);
}
public override void activate () {
var window = new Window (this);
add_window (window);
}
}
public class Window : Gtk.ApplicationWindow {
public Window (Gtk.Application app) {
Object (application: app);
}
construct {
title = "Drag";
set_default_size (640, 480);
var drag_source = new DragSource ();
set_child (drag_source.self);
show ();
}
}
public class DragSource {
public Gtk.Image self;
public DragSource () {
self = new Gtk.Image ();
var drag_controller = new Gtk.DropTarget (GLib.Type.INVALID, Gdk.DragAction.COPY);
drag_controller.set_gtypes ({typeof(File)});
self.add_controller (drag_controller);
drag_controller.on_drop.connect (on_drop);
}
private bool on_drop (GLib.Value val, double x, double y) {
File filename = (File) val;
var file_path = filename.get_path ();
if (val.holds(typeof(File)) == true) {
print ("The dragged object is a file.\n");
if ("png" in file_path || "jpg" in file_path) {
print ("The dragged object is an image.\n");
self.set_from_pixbuf (pixbuf(file_path));
}
else {
print ("The dragged object is NOT an image.\n");
}
}
else {
print ("The dragged object is NOT a file.\n");
return false;
}
return true;
}
private Gdk.Pixbuf pixbuf (string file) {
try {
return new Gdk.Pixbuf.from_file (file);
} catch (Error e) {
error ("%s", e.message);
}
}
}
This compiles and runs. But as soon as I drag an image file to the window, error occurs and the image is not displayed. This are the pictures of what happens. What should happen is, when I drag a png file from my file manager, the dragged image should be the image showing in the GtkImage, which is the main widget of the window.
On my first drag of an image file from my pc, this error shows up:
The dragged object is a file.
The dragged object is an image.
(v:3891): Gtk-CRITICAL **: 08:52:28.861: gtk_image_set_from_pixbuf: assertion 'GTK_IS_IMAGE (image)' failed
On the second drag, this shows up:
(v:3891): Gdk-CRITICAL **: 08:53:33.388: gdk_drop_set_actions: assertion 'priv->state == GDK_DROP_STATE_NONE' failed
The dragged object is a file.
The dragged object is an image.
(v:3891): Gtk-CRITICAL **: 08:53:33.973: gtk_image_set_from_pixbuf: assertion 'GTK_IS_IMAGE (image)' failed
I would really appreciate a help. Thank You!
This is how I would implement your intention
int main (string[] args) {
var app = new App ();
return app.run (args);
}
public class App : Gtk.Application {
public App () {
Object (
application_id: "com.github.ea",
flags : ApplicationFlags.FLAGS_NONE
);
}
public override void activate () {
var window = new Window (this);
window.present ();
}
}
public class Window : Gtk.ApplicationWindow {
public Window (Gtk.Application app) {
Object (application: app);
}
construct {
title = "Drag an Image!";
set_default_size (640, 480);
var image = new Gtk.Image ();
image.vexpand = image.hexpand = true;
var controller = new Gtk.DropTarget (typeof (GLib.File), Gdk.DragAction.COPY);
controller.on_drop.connect ((target, value, x, y) => {
var file = (GLib.File) value;
var filename = file.get_path ();
if (GLib.ContentType.guess (filename, null, null).contains ("image")) {
image.set_from_file (filename);
}
});
image.add_controller (controller);
set_child (image);
}
}
Swift 4, iOS 11 - I have a UITextView that is pre-populated with text but I want users to be able to save any changes they make to the content there. I also have a Save button in the navigation bar and I would like to disable it until the user actually changes the text in the TextView.
I know how to test for empty but I don't know how to test for when the text has been edited. How do I modify the following to test for changes to the content of TextView?
#IBAction func textEditingChanged(_ sender: UITextView) {
updateSaveButtonState()
}
func updateSaveButtonState() {
let descriptionText = descriptionTextView.text ?? ""
saveButton.isEnabled = !descriptionText.isEmpty
}
We'll to use it a dynamic way and not only in single place, i tried to make it easier to implement around the whole app, subclassing the UITextView is one of the only ways we got here #holex has suggested isEdited boolean flag and it gave me an idea, Thanks to that.
Here is the steps to implement it:
First of all set the defaultText of the textView and set the target of the method that will be called when the textView will be edited, so you can customize what ever you want.
#IBOutlet weak var saveButton: UIBarButtonItem!
#IBOutlet weak var textView: SBTextView!{
didSet{
textView.defaultText = "Hello"
textView.setTarget = (selector:#selector(self.updateSaveButtonState),target:self)
}
}
Lets say you'll setup the saveButton in viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
// setup save button action
saveButton.action = #selector(saveAction(_:))
saveButton.target = self
self.updateSaveButtonState()
}
And last is your save action and the selector to update the view using isEdited flag.
//MARK:- Actions
#objc private func updateSaveButtonState(){
// has not been changed keep save button disabled
if self.textView.isEdited == false{
self.saveButton.isEnabled = false
self.saveButton.tintColor = .gray
}else {
// text has been changed enable save button
self.saveButton.isEnabled = true
self.saveButton.tintColor = nil // will reset the color to default
}
}
#objc private func saveAction(_ saveButton:UIBarButtonItem){
self.textView.updateDefaultText()
}
TextView Custom Class:
//
// SBTextView.swift
//
//
// Created by Saad Albasha on 11/17/17.
// Copyright © 2017 AaoIi. All rights reserved.
//
import UIKit
class SBTextView: UITextView,UITextViewDelegate {
var isEdited = false
private var selector : Selector?
private var target : UIViewController?
var setTarget: (selector:Selector?,target:UIViewController?) {
get{
return (selector,target)
}
set(newVal) {
selector = newVal.0
target = newVal.1
}
}
var textViewDefaultText = ""
var defaultText: String {
get {
return textViewDefaultText
}
set(newVal) {
textViewDefaultText = newVal
self.text = newVal
self.isEdited = false
}
}
//MARK:- Life Cycle
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
self.setupTextview()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupTextview()
}
private func setupTextview(){
// setup textview
self.text = textViewDefaultText
self.delegate = self
}
func updateDefaultText(){
self.defaultText = self.text!
// update save button state
target!.perform(self.selector, with: nil, with: nil)
}
//MARK:- Delegate
internal func textViewDidChange(_ textView: UITextView) {
if textViewDefaultText != textView.text! {
isEdited = true
}else {
isEdited = false
}
// update save button state
target!.perform(self.selector, with: nil, with: nil)
}
}
I hope this helps.
I can use
ChoiceDialog<String> dialog = new ChoiceDialog();
dialog.showAndWait();
but i'll have only one choiceBox to use, and I need 3 of this in one dialog. How can i do this?
Here is the answer:
public void showAndWait(Window owner) throws IOException {
Dialog<String> dialog = new Dialog<>();
dialog.getDialogPane().setContent(FXMLLoader.load(getClass().getResource("/resources/customDialog.fxml")));
dialog.getDialogPane().setHeaderText("text");
ButtonType confirm = new ButtonType("ok", ButtonBar.ButtonData.OK_DONE);
ButtonType cancel = new ButtonType("cansel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(cancel, confirm);
dialog.initStyle(StageStyle.UNDECORATED);
dialog.setTitle("title");
dialog.initOwner(owner);
dialog.showAndWait();
}
Looks nice, i make class with this method, and use it class like controller to fxml, so now I can easily use any controls without any troubles
You can build yourself a custom dialog, using the tutorial at http://code.makery.ch/blog/javafx-dialogs-official/
I adapted their custom dialog for three dropdowns; in my case to merge two custom POJO camera objects with make, model and serial number. Feel free to adapt and use my code below.
Set<String> makes = new HashSet<>();
toMerge.stream().forEach((c) -> {
if (c.getMake()!=null && !c.getMake().isEmpty()) {
makes.add(c.getMake());
}
});
if (makes.isEmpty()) {
makes.add("UNKNOWN");
}
Set<String> models = new HashSet<>();
toMerge.stream().forEach((c) -> {
if (c.getModel()!=null && !c.getModel().isEmpty()) {
models.add(c.getModel());
}
});
if (models.isEmpty()) {
models.add("UNKNOWN");
}
Set<String> serials = new HashSet<>();
toMerge.stream().forEach((c) -> {
if (c.getSerial()!=null && !c.getSerial().isEmpty()) {
serials.add(c.getSerialNumber());
}
});
if (serials.isEmpty()) {
serials.add("UNKNOWN");
}
Dialog<HashMap<String, String>> dialog = new Dialog<>();
dialog.setTitle("Merge cameras");
dialog.setHeaderText("Please select the values for the merged camera. You can modify the merged camera later");
// Set the button types.
ButtonType mergeButtonType = new ButtonType("Merge", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(mergeButtonType, ButtonType.CANCEL);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
ComboBox<String> makesBox = new ComboBox<>();
makes.stream().forEach((make) -> {
makesBox.getItems().add(make);
});
makesBox.setValue(makes.iterator().next());
ComboBox<String> modelsBox = new ComboBox<>();
models.stream().forEach((model) -> {
modelsBox.getItems().add(model);
});
modelsBox.setValue(models.iterator().next());
ComboBox<String> serialsBox = new ComboBox<>();
serials.stream().forEach((serial) -> {
serialsBox.getItems().add(serial);
});
serialsBox.setValue(serials.iterator().next());
grid.add(new Label("Make:"), 0, 0);
grid.add(makesBox, 1, 0);
grid.add(new Label("Model:"), 0, 1);
grid.add(modelsBox, 1, 1);
grid.add(new Label("Serial number:"), 0, 2);
grid.add(serialsBox, 1, 2);
dialog.getDialogPane().setContent(grid);
// Convert the result to the desired data structure
dialog.setResultConverter(dialogButton -> {
if (dialogButton == mergeButtonType) {
HashMap<String, String> result = new HashMap<>();
result.put("make", makesBox.getValue());
result.put("model", modelsBox.getValue());
result.put("serial", serialsBox.getValue());
return result;
}
return null;
});
Optional<HashMap<String, String>> result = dialog.showAndWait();
result.ifPresent(r -> {
logger.debug("{}", r);
//TODO: handle result
});
How can i access the ViewController in my DependencyService to present a MFMailComposeViewController? I tried using Application.Context but this seems to be only working on Android. Any advice?
You can present a MFMailComposeViewController by doing a window.RootController.PresentViewController (mail controller, true, null);. Depending on your app architecture, the RootViewController might not be an usable ViewController in the hierarchy. In that case you get a
Warning: Attempt to present <MFMailComposeViewController: 0x16302c30> on <Xamarin_Forms_Platform_iOS_PlatformRenderer: 0x14fd1530> whose view is not in the window hierarchy!
In that case, you have to dig for the concrete ViewController, in my case it is:
var rootController = ((AppDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.ChildViewControllers[0].ChildViewControllers[1].ChildViewControllers[0];
which is a bit wicked, but works (An issue for this have been filed for future fix).
The full solution then looks like:
in your AppDelegate.cs, add this:
public UIWindow Window {
get { return window; }
}
in your PCL project, declare the interface: ISendMailService.cs
public interface ISendMailService
{
void ComposeMail (string[] recipients, string subject, string messagebody = null, Action<bool> completed = null);
}
in your iOS project, implement and register the interface: SendMailService.cs
[assembly: DependencyAttribute(typeof(SendMailService))]
public class SendMailService : ISendMailService
{
public void ComposeMail (string[] recipients, string subject, string messagebody = null, Action<bool> completed = null)
{
var controller = new MFMailComposeViewController ();
controller.SetToRecipients (recipients);
controller.SetSubject (subject);
if (!string.IsNullOrEmpty (messagebody))
controller.SetMessageBody (messagebody, false);
controller.Finished += (object sender, MFComposeResultEventArgs e) => {
if (completed != null)
completed (e.Result == MFMailComposeResult.Sent);
e.Controller.DismissViewController (true, null);
};
//Adapt this to your app structure
var rootController = ((AppDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.ChildViewControllers[0].ChildViewControllers[1].ChildViewControllers[0];
var navcontroller = rootController as UINavigationController;
if (navcontroller != null)
rootController = navcontroller.VisibleViewController;
rootController.PresentViewController (controller, true, null);
}
}
And you can now consume it from your Xamarin.Forms PCL project:
new Button {
Font = Font.SystemFontOfSize (NamedSize.Medium),
Text = "Contact us",
TextColor = Color.White,
BackgroundColor = ColorsAndStyles.LightBlue,
BorderRadius = 0,
Command = new Command (()=>{
var mailservice = DependencyService.Get<ISendMailService> ();
if (mailservice == null)
return;
mailservice.ComposeMail (new [] {"foo#example.com"}, "Test", "Hello, World");
})
}
Use: UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(controller, true, null);
I would like to add an additional answer based off of the KeyWindow not always being the main window. (this occurs when you are presenting your controller after the user has interacted with an action sheet or alert dialog)
public static UIViewController GetCurrentUIController()
{
UIViewController viewController;
var window = UIApplication.SharedApplication.KeyWindow;
if (window == null)
{
throw new InvalidOperationException("There's no current active window");
}
if (window.RootViewController.PresentedViewController == null)
{
window = UIApplication.SharedApplication.Windows
.First(i => i.RootViewController != null &&
i.RootViewController.GetType().FullName
.Contains(typeof(Xamarin.Forms.Platform.iOS.Platform).FullName));
}
viewController = window.RootViewController;
while (viewController.PresentedViewController != null)
{
viewController = viewController.PresentedViewController;
}
return viewController;
}
This will guarantee that you get the Xamarin Forms platform renderer window, then find the foremost presented ViewController and return it for use presenting whatever UI or view controller you need to present.
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(controller, true, null);
This only works in above all solutions
Just for a reference. It took me some time to figure it out how to launch it from modal window.
Here comes the solution:
var rootController = ((AppDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.PresentedViewController;
var navcontroller = rootController as UINavigationController;
if (navcontroller != null)
rootController = navcontroller.VisibleViewController;
rootController.PresentViewController (controller, true, null);
I have problem that I don't seem to be able to solve. I have a created a test project, using MEF and Prism4. I've created a test project where I have 2 views and each of them register themselves inside a region, and also a button in another region. When the button is clicked, I want the view of change to the correct view. The code I think is wrong is below, anyone have any ideas what I am doing wrong here ?
public void Initialize()
{
regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(Views.Module1View));
Button button = new Button() { Content = "Module1" };
button.Click += (o, i) =>
{
var region = this.regionManager.Regions[RegionNames.MainRegion];
if (region != null)
{
region.Activate(typeof(Views.Module1View));
}
};
regionManager.AddToRegion(RegionNames.NavigationRegion, button);
}
I get the following error ...
The region does not contain the specified view.
Parameter name: view
Solved it - amazing what a good nights sleep will do! I had to get the view from the ServiceLocator.
public void Initialize()
{
regionManager.RegisterViewWithRegion(RegionNames.MainRegion, () =>
ServiceLocator.Current.GetInstance<Views.Module2View>());
Button button = new Button() { Content = "Module2" };
button.Click += (o, i) =>
{
var view = ServiceLocator.Current.GetInstance<Views.Module2View>();
var region = this.regionManager.Regions[RegionNames.MainRegion];
if (region != null)
{
region.Activate(view);
}
};
regionManager.AddToRegion(RegionNames.NavigationRegion, button);
}