2015-01-12 69 views
1

我已经以编程方式向我的视图中添加了UITextView,但我无法弄清楚如何在屏幕的垂直中间设置文本。Swift - 以编程方式定位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) 
} 

如何做到这一点的任何建议,将不胜感激。

编辑:只是解决你如何解开你的可选,加载一个字符串和追加一个路径组件,并没有必要使用自我。

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) 
} 
+1

你要设置在屏幕中间的文本不管文本有多长? – gabbler

+0

@gabbler是的,我限制了我的代码的其他部分可以使用多长时间。 – martin

+0

只要确定我已经正确理解了你的意思,你的意思是垂直中间,就像从屏幕/父视图的顶部到底部的平等空间一样? – Emil

回答

0

您可以使用自动布局这个加入下面的约束:

let verticalCenter = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0) 
self.view.addConstraint(verticalCenter) 

此补充说,内self.view水平居中你的TextView的约束。不过在Interface Builder和Storyboard中这样做更容易。

如果你不想使用约束(支持iOS 5中,下),你可以使用autoresizingMasks为TextView的是这样的:

textView.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin 
+0

对不起,说没有帮助的情况下。我已将新代码添加到上述问题中。 – martin

相关问题