我已经以编程方式向我的视图中添加了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)
}
你要设置在屏幕中间的文本不管文本有多长? – gabbler
@gabbler是的,我限制了我的代码的其他部分可以使用多长时间。 – martin
只要确定我已经正确理解了你的意思,你的意思是垂直中间,就像从屏幕/父视图的顶部到底部的平等空间一样? – Emil