我已经以编程方式创建了一个UITextView,但不幸的是,当它从属性检查器拖到Text.storyboard时,它的行为与textview的行为方式不同。 例如:我以编程方式创建的textview中的文字没有"断线"在textview框架的右侧。 虽然文档提到了textContainerInsets,但我似乎无法让它工作。 (Xcode不识别属性)
class ViewController: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)
var textView:UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.view = self.scrollView
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width;
let screenHeight = screenSize.height;
//Create textview
let textView : UITextField = UITextField(frame : CGRect(x:10, y:(screenHeight/2), width: (screenWidth-20), height: (screenHeight/3) ))
textView.backgroundColor = UIColor( red: 0.9, green: 0.9, blue:0.9, alpha: 1.0 )
textView.placeholder = NSLocalizedString("Start typing...", comment: "")
textView.borderStyle = UITextBorderStyle.Line;
// textView.autocorrectionType = .Yes
self.view.addSubview( textView )
}
有没有办法让我的textview中的文字像正常一样?多行而不是一行?
答案 0 :(得分:2)
您在代码中创建了UITextField
,而不是UITextView
。
此:
let textView : UITextField = UITextField(frame : CGRect(x:10, y:(screenHeight/2), width:(screenWidth-20), height: (screenHeight/3) ))
应该是:
let textView : UITextView = UITextView(frame : CGRect(x:10, y:(screenHeight/2), width: (screenWidth-20), height: (screenHeight/3) ))
您似乎也已将textView
声明为您班级中的属性,因此您可能不希望let
位于其中:
textView = UITextView(frame : CGRect(x:10, y:(screenHeight/2), width: (screenWidth-20), height: (screenHeight/3) ))
答案 1 :(得分:2)
这是我如何以编程方式实现您的UITextView -
override func viewDidLoad() {
super.viewDidLoad();
self.view.translatesAutoresizingMaskIntoConstraints = false;
let screenSize: CGRect = UIScreen.mainScreen().bounds;
let screenWidth = screenSize.width;
let screenHeight = screenSize.height;
//Create textview
let textView : UITextView = UITextView(frame : CGRect(x: 10,
y: (screenHeight/2),
width: (screenWidth-20),
height: (screenHeight/3)));
textView.backgroundColor = UIColor( red: 0.9, green: 0.9, blue:0.9, alpha: 1.0 );
textView.text = NSLocalizedString("Start typing... maybe...", comment: "");
//textView.borderStyle: border's are not supported by the UITextView
self.view.addSubview(textView);
return;
}