create text box in document .docx using apache poi - apache-poi
I want create a text box in a document .docx but I didnĀ“t find a method
that help me do it and any example. Someone know how can i do it?
Inserting a real Word Text-box is not fully possible with apache-poi until now. A real Word Text-box is contained in a CTShape from schemasMicrosoftComVml or com.microsoft.schemas.vml. The XML looks like:
<w:r>
<w:pict>
<v:shape style="width:100pt;height:24pt">
<v:textbox>
<w:txbxContent>
<w:p>
<w:r>
<w:t>The TextBox text...</w:t>
</w:r>
</w:p>
</w:txbxContent>
</v:textbox>
</v:shape>
</w:pict>
</w:r>
As you see the namespaces in v:shape and v:textbox are different from the rest.
So if we know and respect this, we can currently insert such CTShape. But only inline with the text. Creating a CTWrap for this is currently not possible, as far as I know, because the CTWrap from the schemasMicrosoftComOfficeWord is not shipped within the poi-ooxml-schemas-3.13-*.jar and the com.microsoft.schemas.vml and com.microsoft.schemas.office classes from ooxml-schemas-1.3.jar need a org.apache.poi.POIXMLTypeLoader which is not shipped with version 3.13.
Example for an inline Textbox:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPicture;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTxbxContent;
import schemasMicrosoftComVml.CTGroup;
import schemasMicrosoftComVml.CTShape;
import org.w3c.dom.Node;
public class CreateWordTextBox {
public static void main(String[] args) throws Exception {
XWPFDocument doc= new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("The Body text: ");
CTGroup ctGroup = CTGroup.Factory.newInstance();
CTShape ctShape = ctGroup.addNewShape();
ctShape.setStyle("width:100pt;height:24pt");
CTTxbxContent ctTxbxContent = ctShape.addNewTextbox().addNewTxbxContent();
ctTxbxContent.addNewP().addNewR().addNewT().setStringValue("The TextBox text...");
Node ctGroupNode = ctGroup.getDomNode();
CTPicture ctPicture = CTPicture.Factory.parse(ctGroupNode);
run=paragraph.createRun();
CTR cTR = run.getCTR();
cTR.addNewPict();
cTR.setPictArray(0, ctPicture);
doc.write(new FileOutputStream("WordTextBox.docx"));
}
}
But a positioned text-frame is possible:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPBdr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFramePr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STXAlign;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STWrap;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
/*
To
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFramePr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STXAlign;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STWrap;
the fully ooxml-schemas-1.3.jar is needed as mentioned in https://poi.apache.org/faq.html#faq-N10025
*/
import java.math.BigInteger;
public class CreateWordTextFrame {
public static void main(String[] args) throws Exception {
XWPFDocument doc= new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("The body text:");
CTSdtContentBlock ctSdtContentBlock = doc.getDocument().getBody().addNewSdt().addNewSdtContent();
CTP ctP = ctSdtContentBlock.addNewP();
ctP.addNewR().addNewT().setStringValue("The TextFrame text...");
CTPPr ctPPr = ctP.addNewPPr();
CTFramePr ctFramePr = ctPPr.addNewFramePr();
ctFramePr.setHAnchor(STHAnchor.TEXT);
ctFramePr.setVAnchor(STVAnchor.TEXT);
ctFramePr.setXAlign(STXAlign.CENTER);
ctFramePr.setWrap(STWrap.AROUND);
ctFramePr.setW(BigInteger.valueOf(4000));
ctFramePr.setHSpace(BigInteger.valueOf(400));
CTPBdr ctPBdr = ctPPr.addNewPBdr();
CTBorder ctBorder = ctPBdr.addNewLeft(); ctBorder.setColor("000000"); ctBorder.setVal(STBorder.SINGLE); ctBorder.setSz(BigInteger.valueOf(4)); ctBorder.setSpace(BigInteger.valueOf(7));
ctBorder = ctPBdr.addNewRight(); ctBorder.setColor("000000"); ctBorder.setVal(STBorder.SINGLE); ctBorder.setSz(BigInteger.valueOf(4)); ctBorder.setSpace(BigInteger.valueOf(7));
ctBorder = ctPBdr.addNewTop(); ctBorder.setColor("000000"); ctBorder.setVal(STBorder.SINGLE); ctBorder.setSz(BigInteger.valueOf(4)); ctBorder.setSpace(BigInteger.valueOf(7));
ctBorder = ctPBdr.addNewBottom(); ctBorder.setColor("000000"); ctBorder.setVal(STBorder.SINGLE); ctBorder.setSz(BigInteger.valueOf(4)); ctBorder.setSpace(BigInteger.valueOf(7));
paragraph = doc.createParagraph();
run=paragraph.createRun();
run.setText("Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... ");
doc.write(new FileOutputStream("WordTextFrame.docx"));
}
}
This needs the fully ooxml-schemas-1.3.jar as mentioned in https://poi.apache.org/faq.html#faq-N10025.
Edit
If we downgrade to ooxml-schemas-1.1.jar - available from http://search.maven.org/#artifactdetails|org.apache.poi|ooxml-schemas|1.1|jar - then a free positionable Text-box is also possible with apache-poi version 3.13.
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPicture;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTxbxContent;
import schemasMicrosoftComVml.CTGroup;
import schemasMicrosoftComVml.CTShape;
import schemasMicrosoftComOfficeWord.CTWrap;
import schemasMicrosoftComOfficeWord.STWrapType;
/*
To
import schemasMicrosoftComOfficeWord.CTWrap;
import schemasMicrosoftComOfficeWord.STWrapType;
ooxml-schemas-1.1.jar is needed - available from http://search.maven.org/#artifactdetails|org.apache.poi|ooxml-schemas|1.1|jar
*/
import org.w3c.dom.Node;
public class CreateWordTextBox {
public static void main(String[] args) throws Exception {
XWPFDocument doc= new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("The Body text: ");
CTGroup ctGroup = CTGroup.Factory.newInstance();
CTShape ctShape = ctGroup.addNewShape();
ctShape.addNewWrap().setType(STWrapType.SQUARE);
ctShape.setStyle("position:absolute;mso-position-horizontal:center;margin-top:40pt;width:100pt;height:24pt");
CTTxbxContent ctTxbxContent = ctShape.addNewTextbox().addNewTxbxContent();
ctTxbxContent.addNewP().addNewR().addNewT().setStringValue("The TextBox text...");
Node ctGroupNode = ctGroup.getDomNode();
CTPicture ctPicture = CTPicture.Factory.parse(ctGroupNode);
run=paragraph.createRun();
CTR cTR = run.getCTR();
cTR.addNewPict();
cTR.setPictArray(0, ctPicture);
paragraph = doc.createParagraph();
run=paragraph.createRun();
run.setText("Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... ");
doc.write(new FileOutputStream("WordTextBox.docx"));
}
}
Edit
Using current apache poi 5.0.0 following is possible:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPicture;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTxbxContent;
import com.microsoft.schemas.vml.CTGroup;
import com.microsoft.schemas.vml.CTShape;
import com.microsoft.schemas.office.word.CTWrap;
import com.microsoft.schemas.office.word.STWrapType;
import org.w3c.dom.Node;
public class CreateWordTextBox {
public static void main(String[] args) throws Exception {
XWPFDocument doc= new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("The Body text: ");
CTGroup ctGroup = CTGroup.Factory.newInstance();
CTShape ctShape = ctGroup.addNewShape();
ctShape.addNewWrap().setType(STWrapType.SQUARE);
ctShape.setStyle("position:absolute;mso-position-horizontal:center;margin-top:40pt;width:100pt;height:24pt");
CTTxbxContent ctTxbxContent = ctShape.addNewTextbox().addNewTxbxContent();
ctTxbxContent.addNewP().addNewR().addNewT().setStringValue("The TextBox text...");
Node ctGroupNode = ctGroup.getDomNode();
CTPicture ctPicture = CTPicture.Factory.parse(ctGroupNode);
run=paragraph.createRun();
CTR cTR = run.getCTR();
cTR.addNewPict();
cTR.setPictArray(0, ctPicture);
paragraph = doc.createParagraph();
run=paragraph.createRun();
run.setText("Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... Lorem ipsum semit color ... ");
FileOutputStream out = new FileOutputStream("WordTextBox.docx");
doc.write(out);
out.close();
doc.close();
}
}
For HWPF (i.e. the old binary doc format) there is a very rudimentary interface via HWPFDocument.getMainTextBoxRange(). I believe it is only suitable for reading, though.
For XWPF (the newer docx format that you asked for) it appears that Text Boxes are always embedded in a Drawing (using DrawingML; please correct me if I am wrong). At least this is how I interpret clauses 17.3.1.40, 20.4.2.37 and 20.4.2.38 of ECMA-376, Part 1. Thus, your method of choice should be XSSFDrawing.createTextbox(). However, I haven't yet come across an easy to use link between this drawing class (which stems from POI's Excel component) and XWPF.
Related
Trying to set up a scrollable view with multiple multiline of text but when app is run, it is running very slow when scrolling
I am trying to set up an Instructions view that will show the instructions to run my app via text (for those who don't quite understand how it works and need step by step instructions). I wrote the following code, but when I ran it, it ran very slow when I opened this particular view and the scrolling was very slow until it just didn't do anything, like a crash without crashing. My code: NavigationView { ScrollView { LazyVStack(alignment: .leading) { padding() Text("Main Screen") .font(.title2) .foregroundColor(.purple) Text("This is the description text for the Main Screen") .padding(.all) .font(.title3) .foregroundColor(.pink) }.padding(.leading) LazyVStack(alignment: .leading) { Text("Log In") .font(.title2) .foregroundColor(.purple) Text("This is the description text for the Login") .padding(.all) .font(.title3) .foregroundColor(.pink) padding() }.padding(.leading) LazyVStack(alignment: .leading) { Text("Workout") .font(.title2) .foregroundColor(.purple) Text("This is the description text for Workouts.") .padding(.all) .font(.title3) .foregroundColor(.pink) padding() }.padding(.leading) LazyVStack(alignment: .leading) { Text("Logout") .font(.title2) .foregroundColor(.purple) Text("This is the description text for Logout") .padding(.all) .font(.title3) .foregroundColor(.pink) padding() } .padding(.leading) LazyVStack(alignment: .leading) { Text("Settings") .font(.title2) .foregroundColor(.purple) Text("This is the description text for Settings") .padding(.all) .font(.title3) .foregroundColor(.pink) padding() } .padding(.leading) } .navigationTitle("Instructions") } The code I had, had a lot more code in the 'description text' than is above and each new category or title consisted of a new LazyVStack block with a set of 2 Texts, as above. The entire view should consists of 8-10 LazyVStack blocks. Below is a diagram of what I am trying to do: Basically, I am just trying to create a scrollable view that just contains text with a title and a description of the title below it. There will be up to 10 titles and descriptions - all text. What am I doing wrong and how I can fix this?
I think the problem is with your padding()s. try removing them. You should add padding to your views like this: Text("content") .padding() as you can see in the documentation, padding(_) is a view modifier and should be called on a View. to add extra space between your components, you can do either: 1- set the space between components of your LazyVStack by passing spacing like this: LazyVStack(alignment: .leading, spacing: 32) { // <- spacing Text("Main Screen") .font(.title2) .foregroundColor(.purple) Text("This is the description text for the Main Screen") .padding(.all) .font(.title3) .foregroundColor(.pink) }.padding(.leading) 2- or set the top padding by using padding(_, _) modifier: LazyVStack(alignment: .leading) { Text("Main Screen") .font(.title2) .foregroundColor(.purple) .padiing(.top, 32) // <-- padding Text("This is the description text for the Main Screen") .padding(.all) .font(.title3) .foregroundColor(.pink) .padding(.top, 32) // <-- padding }.padding(.leading)
Can not run sample test Koin
I want to run sample test from this site https://insert-koin.io/docs/2.0/getting-started/junit-test/ class HelloAppTest : AutoCloseKoinTest() { val model by inject<HelloMessageData>() val service by inject<HelloService>() #Before fun before() { startKoin { modules(helloModule) } } #Test fun tesKoinComponents() { val helloApp = HelloApplication() helloApp.sayHello() assertEquals(service, helloApp.helloService) assertEquals("Hey, ${model.message}", service.hello()) } } But it gives following error : No tests found for given includes: [HelloAppTest] (filter.includeTestsMatching) My gradle file is this : import org.jetbrains.kotlin.gradle.tasks.KotlinCompile buildscript { dependencies { classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.31") } } plugins { kotlin("jvm") version "1.3.21" // duplicate for variable } group = "adf" version = "1.0-SNAPSHOT" repositories { mavenCentral() jcenter() } dependencies { implementation(kotlin("stdlib-jdk8")) implementation("org.koin:koin-core:2.0.0-rc-1") testCompile("org.koin:koin-test:2.0.0-rc-1") } tasks.withType<KotlinCompile> { kotlinOptions.jvmTarget = "1.8" } tasks.withType<Test> { useJUnitPlatform() } How to handle it? Anybody, please help me And this is just for stackoverflow.com: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
you need to include following imports: testImplementation "junit:junit:4.12"
C++/CX No Suitable Copy Constructor
I have a problem with C++/CX. I'm trying to create a class that is actually a collection of other Class. The class is declared here in the header file: #pragma once namespace AdeptlyAdaptiveLayout { public ref class NewsItem sealed { public: NewsItem(int init_Id, Platform::String^ init_Category, Platform::String^ init_Headline, Platform::String^ init_Subhead, Platform::String^ init_DateLine, Platform::String^ Image); property int Id; property Platform::String^ Category; property Platform::String^ Headline; property Platform::String^ Subhead; property Platform::String^ DateLine; property Platform::String^ Image; }; public ref class NewsItemCollection sealed { public: Platform::Collections::Vector<NewsItem> getNewsItems(); }; } and this is the source file #include "pch.h" #include "NewsItem.h" using namespace Platform; using namespace Platform::Collections; namespace AdeptlyAdaptiveLayout { NewsItem::NewsItem(int init_Id, String^ init_Category, String^ init_Headline, String^ init_Subhead, String^ init_DateLine, String^ init_Image) { Id = init_Id; Category = init_Category; Headline = init_Headline; Subhead = init_Subhead; DateLine = init_DateLine; Image = init_Image; } Vector<NewsItem> NewsItemCollection::getNewsItems() { Vector<NewsItem> temp; temp.Append(*ref new NewsItem(1, "Financial", "Lorem Ipsum", "doro sit amet", "Nunc tristique nec", "Assets/Financial1.png")); temp.Append(*ref new NewsItem(2, "Financial", "Etiam ac felis viverra", "vulputate nisl ac, aliquet nisi", "tortor porttitor, eu fermentum ante congue", "Assets/Financial2.png")); temp.Append(*ref new NewsItem(3, "Financial", "Integer sed turpis erat", "Sed quis hendrerit lorem, quis interdum dolor", "in viverra metus facilisis sed", "Assets/Financial3.png")); temp.Append(*ref new NewsItem(4, "Financial", "Proin sem neque", "aliquet quis ipsum tincidunt", "Integer eleifend", "Assets/Financial4.png" )); temp.Append(*ref new NewsItem(5, "Financial", "Mauris bibendum non leo vitae tempor", "In nisl tortor, eleifend sed ipsum eget", "Curabitur dictum augue vitae elementum ultrices", "Assets/Financial5.png" )); temp.Append(*ref new NewsItem(6, "Food", "Lorem ipsum", "dolor sit amet", "Nunc tristique nec", "Assets/Food1.png" )); temp.Append(*ref new NewsItem(7, "Food", "Etiam ac felis viverra", "vulputate nisl ac, aliquet nisi", "tortor porttitor, eu fermentum ante congue", "Assets/Food2.png" )); temp.Append(*ref new NewsItem(8,"Food", "Integer sed turpis erat", "Sed quis hendrerit lorem, quis interdum dolor", "in viverra metus facilisis sed","Assets/Food3.png" )); temp.Append(*ref new NewsItem(9, "Food","Proin sem neque", "aliquet quis ipsum tincidunt", "Integer eleifend", "Assets/Food4.png" )); temp.Append(*ref new NewsItem(10, "Food", "Mauris bibendum non leo vitae tempor", "In nisl tortor, eleifend sed ipsum eget", "Curabitur dictum augue vitae elementum ultrices", "Assets/Food5.png" )); return temp; } } The problem is that I keep having this error message "class 'AdeptlyAdaptiveLayout::NewsItem' has no suitable copy constructor". I don't have any idea what I've done wrong. Can you guys me a clue?
Okay, I found the answer now. I've changed the type from Vector to IVector, explicitly create the copy constructor, and adding several changes in the implementation. Here is the changed code in the header and in the source. Header: namespace AdeptlyAdaptiveLayout { public ref class NewsItem sealed { public: NewsItem(int init_Id, Platform::String^ init_Category, Platform::String^ init_Headline, Platform::String^ init_Subhead, Platform::String^ init_DateLine, Platform::String^ Image); NewsItem(NewsItem^ obj); property int Id; property Platform::String^ Category; property Platform::String^ Headline; property Platform::String^ Subhead; property Platform::String^ DateLine; property Platform::String^ Image; }; public ref class NewsItemCollection sealed { public: Windows::Foundation::Collections::IVector<NewsItem^>^ getNewsItems(); }; } Source: #include "pch.h" #include "NewsItem.h" using namespace Platform; using namespace Platform::Collections; using namespace Windows::Foundation::Collections; namespace AdeptlyAdaptiveLayout { NewsItem::NewsItem(int init_Id, String^ init_Category, String^ init_Headline, String^ init_Subhead, String^ init_DateLine, String^ init_Image) { Id = init_Id; Category = init_Category; Headline = init_Headline; Subhead = init_Subhead; DateLine = init_DateLine; Image = init_Image; } NewsItem::NewsItem(NewsItem^ obj) { this->Category = obj->Category; this->DateLine = obj->DateLine; this->Headline = obj->Headline; this->Id = obj->Id; this->Image = obj->Image; this->Subhead = obj->Subhead; } IVector<NewsItem^>^ NewsItemCollection::getNewsItems() { IVector<NewsItem^>^ temp = ref new Vector<NewsItem^> (); temp->Append(ref new NewsItem(1, "Financial", "Lorem Ipsum", "doro sit amet", "Nunc tristique nec", "Assets/Financial1.png")); temp->Append(ref new NewsItem(2, "Financial", "Etiam ac felis viverra", "vulputate nisl ac, aliquet nisi", "tortor porttitor, eu fermentum ante congue", "Assets/Financial2.png")); temp->Append(ref new NewsItem(3, "Financial", "Integer sed turpis erat", "Sed quis hendrerit lorem, quis interdum dolor", "in viverra metus facilisis sed", "Assets/Financial3.png")); temp->Append(ref new NewsItem(4, "Financial", "Proin sem neque", "aliquet quis ipsum tincidunt", "Integer eleifend", "Assets/Financial4.png" )); temp->Append(ref new NewsItem(5, "Financial", "Mauris bibendum non leo vitae tempor", "In nisl tortor, eleifend sed ipsum eget", "Curabitur dictum augue vitae elementum ultrices", "Assets/Financial5.png" )); temp->Append(ref new NewsItem( 6, "Food", "Lorem ipsum", "dolor sit amet", "Nunc tristique nec", "Assets/Food1.png" )); temp->Append(ref new NewsItem(7, "Food", "Etiam ac felis viverra", "vulputate nisl ac, aliquet nisi", "tortor porttitor, eu fermentum ante congue", "Assets/Food2.png" )); temp->Append(ref new NewsItem(8,"Food", "Integer sed turpis erat", "Sed quis hendrerit lorem, quis interdum dolor", "in viverra metus facilisis sed","Assets/Food3.png" )); temp->Append(ref new NewsItem(9, "Food","Proin sem neque", "aliquet quis ipsum tincidunt", "Integer eleifend", "Assets/Food4.png" )); temp->Append(ref new NewsItem(10, "Food", "Mauris bibendum non leo vitae tempor", "In nisl tortor, eleifend sed ipsum eget", "Curabitur dictum augue vitae elementum ultrices", "Assets/Food5.png" )); return temp; } } However, I still do not understand why it works. I think I'm going to do an in-depth research on this.
When you provided the constructor with this constructor signature: NewsItem(int init_Id, Platform::String .... ... the compiler will no longer synthesize the default ctors for you. You now need to specify them yourself in this case. https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx If any non-default constructors are declared, the compiler does not provide a default constructor
How to display a string with a delay in between words in Swift?
So I've tried using Matt's delay code but it does not seem to fit my purpose. I'm writing a Swift app and would like to be able to display a string (say a word at a time) with a delay in between. Anyone have any suggestions?
This will give you a delay of four seconds between two words. You dont say how many words you need to do this with and without any context or you posting any code its not easy to understand your requirements. However this will provide a delay between two strings self.mystring.text = "some word" let seconds = 4.0 let delay = seconds * Double(NSEC_PER_SEC) // nanoseconds per seconds var dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue(), { // Performed with delay self.mystring.text = "a different word" })
class ViewController: UIViewController { #IBOutlet weak var myTypeWriter: UITextView! let words = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. Hello World !!!".componentsSeparatedByString(" ") var counter = 0 var timer:NSTimer? // create a method to add one word at a time to your text view func addWord(){ // make sure you only update your text field if you have a corresponding item in your array if counter < words.count { myTypeWriter.text = "\(myTypeWriter.text) \(words[counter])" // invalidate your timer when it is finished } else { timer?.invalidate() } counter++ } override func viewDidLoad() { super.viewDidLoad() timer = NSTimer.scheduledTimerWithTimeInterval(0.25, target: self, selector: "addWord", userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
UIMenuController and UITextView selected text
first i am using this UITextView class textViewClass.h #interface textViewClass : UITextView textViewClass.m #implementation textViewClass - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { NSMutableArray *items = [[[UIMenuController sharedMenuController] menuItems] mutableCopy]; if (!items) items = [[NSMutableArray alloc] init]; UIMenuItem *menuItem; menuItem = [[UIMenuItem alloc] initWithTitle:#"Add note" action:#selector(doSomethingHere:)]; [items addObject:menuItem]; [[UIMenuController sharedMenuController] setMenuItems:items]; } return self; } - (void)doSomethingHere:(UITextView *)textView { NSLog(#"add note: "); } And in MainViewController.h #import "textViewClass.h" #interface testViewController : UIViewController <UITextViewDelegate> #property (strong, nonatomic) IBOutlet textViewClass *myTextView; And in MainViewController.m - (void)viewDidLoad { [super viewDidLoad]; [self.myTextView setEditable:NO]; [self.myTextView setDelegate:self]; [self.myTextView setText:#"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."]; } #pragma mark - UITextView Delegate - (void)textViewDidChangeSelection:(UITextView *)textView { NSString *string = [self.myTextView textInRange:textView.selectedTextRange]; NSLog(#"%#", string); } I want to show 'Add note' when i selected some text in myTextView and copy this selection to clipboard and do some action as i want.
hmm you need two corrections. The first is: you have to implement the UIResponder method like this in your custom UITextView class. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == #selector(doSomethingHere:) || action == #selector(copy:)) { if (self.selectedRange.length > 0) { return YES; } } return NO; } here you are filtering the actions with the code which has been defined under the UIResponderStandardEditActions informal protocol. if (action == #selector(doSomethingHere:) || action == #selector(copy:)) if you only need yourAction only then do if (action == #selector(doSomethingHere:)) Second correction: if you implement the protocol like this - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { return YES; } you will see all possible commands by default therefor: Either filter it by selector or add your own command only like this, UIMenuItem *menuItem; menuItem = [[UIMenuItem alloc] initWithTitle:#"Add note" action:#selector(doSomethingHere:)]; [items addObject:menuItem]; [[UIMenuController sharedMenuController] setMenuItems:#[menuItem]]; Hope it will help you... NB: For more information please check NSHipster