我已經以編程方式向我的視圖中添加了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