How can i present uiview (xib) as alert view in swift
1.Fetch the XIB file object.
let alert = NSBundle.mainBundle().loadNibNamed("Alert", owner: self, options: nil).last as! UIView
2.Compose the convenience methods.
static func showAlert() {
let windows = UIApplication.sharedApplication().windows
let lastWindow = windows.last
alert.frame = UIScreen.mainScreen().bounds
lastWindow?.addSubview(alert)
}
static func removeAlert() {
alert.removeFromSuperview()
}
3.Call the methods.
//showing alert
ClassName.showAlert()
//remove alert
ClassName.removeAlert()
Present & Remove XIB as UIView over KeyWindow
You only create the view once using:
let AlertScreen = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert
You are presenting the save view over and over again. If you want to fresh views, you need to create a new view every time you present it.
var currentAlert: Alert?
func showAlert (LeftButton: String, RightButton: String) {
removeAlert()
currentAlert = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert
currentAlert.frame = UIScreen.main.bounds
currentAlert.LeftButton.setTitle(LeftButton, for: .normal)
currentAlert.RightButton.setTitle(RightButton, for: .normal)
UIApplication.shared.keyWindow?.addSubview(currentAlert)
}
func removeAlert() {
currentAlert?.removeFromSuperView()
currentAlert = nil
}
how to show xib view when tap on textfield right button
I tried with your code snippet and I got bad access error. Try removing the custom class (CustomeView) of that xib file and set the CustomeView
view class in File's Owner
of that xib file. Also check your messageText
and contentView
outlet object type should be the File's Owner
.
Custom Alert in Swift
First of all you should never touch window
on iOS. Except for extremely rare special cases.
You can create in your .xib a view with transparent or semi-transparent background. Then you can define a protocol to present this view:
protocol AlertPresenting {}
extension AlertPresenting {
func showAlert(_ onView: UIView) {
if let alert = Bundle.main.loadNibNamed("AlertView", owner: nil, options: nil)![0] as? AlertView {
alert.translatesAutoresizingMaskIntoConstraints = false
onView.addSubview(alert)
//here define constraints
onView.bringSubviewToFront(alert)
}
}
}
Then you can use it on any viewController
:
class MyViewController: UIViewController, AlertPresenting {
func someFunction() {
showAlert(onView: self.view)
}
}
The alert will be above all the views
.
how to notify a UIViewController that a button was clicked in a xib file using a delegate in swift?
Check this out, you can do it like this.
Pop.swift
@objc protocol AnswerDelegate {
func isCorrectAnswer()
}
class Pop: UIView {
var answerDelegate: AnswerDelegate?
class func instanceFromNib() -> Pop {
return UINib(nibName: "Pop", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! Pop
}
@IBAction func sendDataToDbAction(_ sender: Any)
{
if(answer == false) {
//Alert
}
else {
answerDelegate?.isCorrectAnswer()
}
}
}
Controller:
class ViewController: UIViewController, AnswerDelegate {
func isCorrectAnswer() {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let popView = Pop.instanceFromNib()
popView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
popView.answerDelegate = self
self.view.addSubview(popView)
}
}
How to create my own UIAlertController in Swift 5?
An alert is nothing but a presented view controller. So make your own view controller and call present
. It's as simple as that.
XIB view not showing with correct layout [iOS Swift]
For anyone facing the same difficulties as me, I was able to accomplish the wanted result.
I used AutoLayouts as suggested by @HAK. But instead of writing my own NSLayoutConstraint
I used roberthein library called TinyConstraints.
Basically, I used as follow:
Instead of
NSLayoutConstraint.activate([
alertView.topAnchor.constraint(equalTo: superview.topAnchor, constant: 0),
alertView.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: 0),
alertView.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: 0),
alertView.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant:
0)])
with TinyConstraints:
alertView.edges(to: superview)
That´s it
adding a custom view to a alert view
for all who having this problem,
i have followed this link..and for the star marks, i used this..
all you have to do is add below files to the project
- CustomIOS7AlertView.h
- CustomIOS7AlertView.m
- JSFavStarControl.h
- JSFavStarControl.m
and put below code where you want to pop up the alert view
// Here we need to pass a full frame
CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
// Add some custom content to the alert view
[alertView setContainerView:[self createDemoView]];
// Modify the parameters
[alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"Close1", @"Close2", @"Close3", nil]];
[alertView setDelegate:self];
// You may use a Block, rather than a delegate.
[alertView setOnButtonTouchUpInside:^(CustomIOS7AlertView *alertView, int buttonIndex) {
NSLog(@"Block: Button at position %d is clicked on alertView %d.", buttonIndex, [alertView tag]);
[alertView close];
}];
[alertView setUseMotionEffects:true];
// And launch the dialog
[alertView show];
and inside the method of createDemoView,you have to implement your customised view.in my case it is like this
UIView *demoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 100)];
//alertView.tag=2;
UILabel *rateLbl=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 290, 45)];
rateLbl.backgroundColor=[UIColor clearColor];
rateLbl.font=[UIFont boldSystemFontOfSize:15];
rateLbl.text=@"Rate";
UILabel *cmntLable=[[UILabel alloc]initWithFrame:CGRectMake(10, 45, 290, 45)];
cmntLable.backgroundColor=[UIColor clearColor];
cmntLable.font=[UIFont boldSystemFontOfSize:15];
cmntLable.text=@"Add Comment";
UIImage *dot, *star;
dot = [UIImage imageNamed:@"dot.png"];
star = [UIImage imageNamed:@"star.png"];
JSFavStarControl *rating = [[JSFavStarControl alloc] initWithLocation:CGPointMake(150, 20) dotImage:dot starImage:star];
[rating addTarget:self action:@selector(updateRating:) forControlEvents:UIControlEventValueChanged];
UILabel *lblAlertTItle=[[UILabel alloc]initWithFrame:CGRectMake(5, 5, 290, 45)];
lblAlertTItle.backgroundColor=[UIColor clearColor];
lblAlertTItle.textAlignment=UITextAlignmentCenter;
lblAlertTItle.font=[UIFont boldSystemFontOfSize:18];
lblAlertTItle.text=@"Choose your sharing option";
UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(150, 57, 100, 25)];
text.backgroundColor=[UIColor whiteColor];
//[demoView addSubview:lblAlertTItle];
[demoView addSubview:text];
[demoView addSubview:rating];
[demoView addSubview:rateLbl];
[demoView addSubview:cmntLable];
return demoView;
so my output is like this.
use it and have fun :)
thank you for everyone who helped me.
Related Topics
Why HTML5 Video Doesn't Play in iOS 8 Webapp(Webview)
How to Pair And/Or Bond to Ble on iOS Using Swift Code and an Hm-10 So Data Sent Is Encrypted
"Reached the Max Number of Texture Atlases, Can Not Allocate More" Using Google Maps
How to Make a Reusable Tableview for Different Screens in the Same Application
Swift: Iboutlets Are Nil in Custom Cell
How to Present Uiview (Xib) as Alert View in Swift
Why Wkwebview Doesn't Display Videos? - Swift 3
Fixing Low Fps in Swift Playground
How Is a Swift Cgvector Created with Dx and Dy (Derivative)
Urlsession.Shared.Datatask VS Datataskpublisher, When to Use Which
Map Object into 2D Array Swift for Tableview Sections
How to Handle a File Sent with 'Open In...' from Another App to My Own iOS App
How to Animate Dark Mode Change in iOS
Using Auto Layout to Have UIlabel and UItextfield Next to Each Other
Can't Add a New iOS Version for My App
Firebase Database Not Equal Request - Alternative Solution (For iOS)