【发布时间】:2015-03-10 00:18:01
【问题描述】:
我以编程方式将 UITextView 添加到我的视图中,但我不知道如何在屏幕的垂直中间设置文本。
我的代码如下所示:
var textView: UITextView?
textView = UITextView(frame: view.bounds)
if let theTextView = textView{
let blurEffect = UIBlurEffect(style: .Dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame.size = CGSize(width: self.view.frame.width, height: self.view.frame.height)
blurView.center = view.center
blurView.tag = 1
theTextView.text = NSString(contentsOfFile: NSTemporaryDirectory() + "\(fileRef).txt", encoding: NSUTF8StringEncoding, error: nil) as String
theTextView.font = UIFont.systemFontOfSize(16)
theTextView.tag = 2
theTextView.textColor = UIColor.whiteColor()
theTextView.insertSubview(blurView, atIndex: 0)
theTextView.textAlignment = NSTextAlignment.Center
view.addSubview(theTextView)
}
任何关于如何做到这一点的建议将不胜感激。
编辑:刚刚修复了你必须如何解开你的可选,加载一个字符串并附加一个路径组件,并且不需要使用 self。
var textView: UITextView?
textView = UITextView(frame: UIScreen.mainScreen().bounds)
if let textView = textView {
let verticalCenter = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0)
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
blurView.frame.size = CGSize(width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height)
blurView.center = view.center
blurView.tag = 1
textView.font = UIFont.systemFontOfSize(16)
textView.tag = 2
textView.text = String(contentsOfURL: NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("\(fileRef).txt"))!, encoding: NSUTF8StringEncoding, error: nil)
textView.textColor = UIColor.whiteColor()
textView.insertSubview(blurView, atIndex: 0)
textView.textAlignment = .Center
view.addSubview(textView)
view.addConstraint(verticalCenter)
}
【问题讨论】:
-
你想把文字设置在屏幕中间不管文字多长?
-
@gabbler 是的,我已经限制了它在我的代码的其他部分中的长度。
-
只是确保我理解正确,你的意思是垂直中间,如屏幕/父视图从上到下的相等空间?
-
@Emil 是的,没错。
标签: ios swift uitextview centering