在我写的应用程序中,我必须显示许多不同文本的不同页面;我宁愿不使用结构基本相同的许多不同观点。
我的想法是,我有一个用于显示纯文本内容的视图,并以编程方式更改标题(显示在导航栏中)和基于按下打开视图的按钮的内容。
我可以通过@IBOutlet将UITextView链接到变量,但我不确定如何引用正在加载的视图来更改它。
答案 0 :(得分:0)
如何在目标控制器中为内容和标题创建两个属性,并根据按钮单击填充值。这是这个要求的简单演示。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
self.addButtons()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Add Buttons
func addButtons() {
var button1 = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button1.setTitle("Content 1", forState: UIControlState.Normal)
button1.backgroundColor = UIColor.redColor()
button1.tag = 1
button1.addTarget(self, action : "showContent:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button1)
var button2 = UIButton(frame: CGRect(x: 100, y: 200, width: 100, height: 50))
button2.setTitle("Content 2", forState: UIControlState.Normal)
button2.backgroundColor = UIColor.blueColor()
button2.tag = 2
button2.addTarget(self, action : "showContent:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button2)
}
func showContent(sender: UIButton!) {
var displayContentController = DisplayContentController()
switch (sender.tag) {
case 1:
displayContentController.content = "Test Content 1"
displayContentController.titleText = "Content1"
break;
case 2:
displayContentController.content = "Test Content 2"
displayContentController.titleText = "Content2"
break;
default:
break;
}
self.presentViewController(displayContentController, animated: true,completion: nil)
}
}
class DisplayContentController:UIViewController {
var contentView:UITextView?
var titleLabel:UILabel?
var content: String?
var titleText: String?
override func viewDidLoad() {
super.viewDidLoad()
self.addTextView()
self.addTitleLabel()
titleLabel?.text = titleText
contentView?.text = content
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- Add UILabel
func addTitleLabel() {
titleLabel = UILabel(frame: CGRect(x: 100, y: 5, width: 100, height: 50))
titleLabel?.textColor = UIColor.whiteColor()
self.view.addSubview(titleLabel!)
}
//MARK:- Add UITextView
func addTextView() {
contentView = UITextView(frame: CGRect(x: 5, y: 60, width: 250, height: 250))
self.view.addSubview(contentView!)
}
}
答案 1 :(得分:0)
如果您在故事板中使用segues,则可以将segue
的{{1}}作为您拥有的视图控制器类型并将信息传递给它。
destinationController