Skip to content

Instantly share code, notes, and snippets.

@bennagar
Created February 16, 2016 23:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennagar/c0cd618bcd23c4c2dadf to your computer and use it in GitHub Desktop.
Save bennagar/c0cd618bcd23c4c2dadf to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let showAlertButton = UIButton(type: UIButtonType.Custom)
showAlertButton.frame = CGRectMake(0, 0, 100, 40)
showAlertButton.setTitle("Show Alert", forState: .Normal)
showAlertButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(showAlertButton)
showAlertButton.center = self.view.center
showAlertButton.addTarget(self, action: "showAlert", forControlEvents: UIControlEvents.TouchUpInside)
}
let alertController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: .Alert)
let textView = UITextView(frame: CGRect.zero)
func showAlert() {
let saveAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
saveAction.enabled = false
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.view.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions.New, context: nil)
NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidChangeNotification, object: textView, queue: NSOperationQueue.mainQueue()) { (notification) in
saveAction.enabled = self.textView.text != ""
}
textView.backgroundColor = UIColor.greenColor()
alertController.view.addSubview(self.textView)
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "bounds"{
if let rect = (change?[NSKeyValueChangeNewKey] as? NSValue)?.CGRectValue(){
let margin:CGFloat = 8.0
textView.frame = CGRectMake(rect.origin.x + margin, rect.origin.y + margin, CGRectGetWidth(rect) - 2*margin, CGRectGetHeight(rect) / 2)
textView.bounds = CGRectMake(rect.origin.x + margin, rect.origin.y + margin, CGRectGetWidth(rect) - 2*margin, CGRectGetHeight(rect) / 2)
}
}
}
}
@bennagar
Copy link
Author

Still locking for way to get the height of the marked view, when I have it I can just replace the /2 with the correct height.
screen shot 2016-02-16 at 3 29 55 pm

@sugimotoak
Copy link

It must removeObserver in saveAction and cancelAction of Handler.

alertController.view.removeObserver(self, forKeyPath: "bounds")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment