【问题标题】:Having a button add text to a UITextField in swift让按钮快速将文本添加到 UITextField
【发布时间】:2015-03-19 02:31:11
【问题描述】:

我正在向 twitter 应用程序创建帖子,并希望通过可选择的按钮将各种文本添加到 UITextField。 UIButton 用于各种主题标签,以加快编写推文的过程。我尝试了几个在 Stack 上找到的解决方案,但似乎都没有,而且它们都在 Objective-C 中。

点击按钮前撰写推文视图的屏幕截图。

http://postimg.org/image/5qoyk6673/

选择按钮并将文本添加到文本字段后撰写推文视图的屏幕截图。

http://postimg.org/image/vp08wsa6b/fa7c7a83/

class TweetComposeViewControler: UIViewController, UITextViewDelegate {
var selectedAccount : ACAccount!

@IBOutlet var tweetContent: UITextView!

@IBAction func specializedButton(sender: UIButton) {
    tweetContent.text = sender as UIButton
    tweetContent.text.stringByAppendingString(specializedButton(titleLabel.text))

}

func insertHashtag(sender: UIButton!) {
    tweetContent.text = tweetContent.text.stringByAppendingString(sender.titleLabel.text)
}

【问题讨论】:

  • 我建议发布您当前的代码。
  • class TweetComposeViewControler: UIViewController, UITextViewDelegate { var selectedAccount : ACAccount! @IBOutlet var tweetContent: UITextView! @IBAction func specializedButton(sender: AnyObject) { tweetContent.text = specializedButton.titleLabel.text } override func viewDidLoad() { super.viewDidLoad() self.tweetContent.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }

标签: ios swift twitter


【解决方案1】:

您可以将 UITextFields 文本设置为 UIButton 的标题:

txtField.text = hashTagButton.titleLabel.text

如果你想附加文本:

txtField.text = textField.text.stringByAppendingString(hashTagButton.titleLabel.text)

为了让您的按钮在按下它们时更新文本,您需要为按下按钮时添加一个目标选择器。这可以通过 Storyboard 或以编程方式完成。

以编程方式

您可以使用以下方法将相同的选择器添加到所有按钮:

 hashtagButton.addTarget(self, action: Selector("insertHashtag:"), forControlEvents: .TouchUpInside)

只要按下hashtagButton,就会调用insertHashtag 函数。由于选择器末尾的:,它也会将自己作为参数传递,因此您可以使用它来获取按钮的标题,而不是为每个按钮创建不同的选择器。

func insertHashtag(sender: UIButton!) {
   txtField.text = textField.text.stringByAppendingString(sender.titleLabel!.text)
}

使用 IBAction

@IBAction func insertHashtag(sender: AnyObject) {
    txtField.text = sender as UIButton 
    textField.text.stringByAppendingString(btn.titleLabel!.text)
}

在这里,您将 sender 参数转换为 UIButton,因为您知道 UIButton 是调用它的对象的类型。

如果您知道只有 UIButton 会导致此方法,您可以这样做:

@IBAction func insertHashtag(btn: UIButton ) {
    txtField.text = sender as UIButton 
    textField.text.stringByAppendingString(btn.titleLabel!.text)
}

回复您的更新 您添加的代码需要修改为如下所示:

@IBAction func specializedButton(sender: UIButton) {
    tweetContent.text.stringByAppendingString(sender.titleLabel!.text)   
}

这里sender 是您的 UIButton,您将它作为 UIButton 传递,因此您无需转换它。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-12-07
  • 2010-09-24
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 2015-04-15
相关资源
最近更新 更多