how can I fix this? tells me that viewDidLoad was declared 2 times but as I can unify the whole process ?
import UIKit
import MessageUI
import CoreData
import MediaPlayer
import AVFoundation
class ViewController: UIViewController, UISearchBarDelegate, MFMailComposeViewControllerDelegate, MPMediaPickerControllerDelegate, AVAudioPlayerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
title = "Media picker..."
buttonPickAndPlay = UIButton.buttonWithType(.System) as? UIButton
if let pickAndPlay = buttonPickAndPlay{
pickAndPlay.frame = CGRect(x: 0, y: 0, width: 200, height: 37)
pickAndPlay.center = CGPoint(x: view.center.x, y: view.center.y - 50)
pickAndPlay.setTitle("Pick and Play", forState: .Normal)
pickAndPlay.addTarget(self,
action: "displayMediaPickerAndPlayItem",
forControlEvents: .TouchUpInside)
view.addSubview(pickAndPlay)
}
buttonStopPlaying = UIButton.buttonWithType(.System) as? UIButton
if let stopPlaying = buttonStopPlaying{
stopPlaying.frame = CGRect(x: 0, y: 0, width: 200, height: 37)
stopPlaying.center = CGPoint(x: view.center.x, y: view.center.y + 50)
stopPlaying.setTitle("Stop Playing", forState: .Normal)
stopPlaying.addTarget(self,
action: "stopPlayingAudio",
forControlEvents: .TouchUpInside)
view.addSubview(stopPlaying)
}
}
#IBOutlet weak var Subject: UITextField!
#IBOutlet weak var Body: UITextView!
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
searchBar?.delegate = self
let url = NSURL(string: "http://www.google.com")
let request = NSURLRequest(URL: url!)
webView?.scalesPageToFit = true
webView?.loadRequest(request)
}
}
Just move the body of one of the two into the other one, except for this line super.viewDidLoad(), which must be called once:
override func viewDidLoad() {
super.viewDidLoad()
title = "Media picker..."
buttonPickAndPlay = UIButton.buttonWithType(.System) as? UIButton
if let pickAndPlay = buttonPickAndPlay{
pickAndPlay.frame = CGRect(x: 0, y: 0, width: 200, height: 37)
pickAndPlay.center = CGPoint(x: view.center.x, y: view.center.y - 50)
pickAndPlay.setTitle("Pick and Play", forState: .Normal)
pickAndPlay.addTarget(self,
action: "displayMediaPickerAndPlayItem",
forControlEvents: .TouchUpInside)
view.addSubview(pickAndPlay)
}
buttonStopPlaying = UIButton.buttonWithType(.System) as? UIButton
if let stopPlaying = buttonStopPlaying{
stopPlaying.frame = CGRect(x: 0, y: 0, width: 200, height: 37)
stopPlaying.center = CGPoint(x: view.center.x, y: view.center.y + 50)
stopPlaying.setTitle("Stop Playing", forState: .Normal)
stopPlaying.addTarget(self,
action: "stopPlayingAudio",
forControlEvents: .TouchUpInside)
view.addSubview(stopPlaying)
}
///
searchBar?.delegate = self
let url = NSURL(string: "http://www.google.com")
let request = NSURLRequest(URL: url!)
webView?.scalesPageToFit = true
webView?.loadRequest(request)
}
Just curios, why did you declare that method twice?
Related
Everything works fine, but when I try to call the createSecondContainer () method from configureAddButton() it doesn't work. That is, pressing the button itself does not work.
override func viewDidLoad() {
super.viewDidLoad()
configureMainContainer()
}
func configureMainContainer(){
view.addSubview(mainContainer)
let frame = CGRect(x: view.bounds.midX - 60, y: view.bounds.midY, width: 120, height: 40)
mainContainer.frame = frame
mainContainer.addTarget(self, action: #selector(showAlert), for: .touchUpInside)
configureAddButton()
}
func configureAddButton(){
mainContainer.addSubview(addButton)
let frame = CGRect(x: mainContainer.bounds.maxX + 5, y: mainContainer.bounds.midY / 2, width: 20, height: 20)
addButton.frame = frame
addButton.addTarget(self, action: #selector(createSecondContainer), for: .touchUpInside)
}
#objc func createSecondContainer(){
print("something to complete")
}
You can use this Code working fine
import UIKit
class ViewController: UIViewController {
let mainContainer = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
configureMainContainer()
}
func configureMainContainer(){
let frame = CGRect(x: view.bounds.midX - 60, y: view.bounds.midY, width: 120, height: 40)
mainContainer.frame = frame
mainContainer.addTarget(self, action: #selector(showAlert), for: .touchUpInside)
mainContainer.backgroundColor = UIColor.red
self.view.addSubview(mainContainer)
configureAddButton()
}
#objc func showAlert() {
// Your Alert Code here
}
func configureAddButton(){
let addButton = UIButton()
let frame = CGRect(x: mainContainer.bounds.midX, y: mainContainer.bounds.midY / 2, width: 20, height: 20)
addButton.frame = frame
addButton.addTarget(self, action: #selector(createSecondContainer), for: .touchUpInside)
addButton.backgroundColor = UIColor.blue
mainContainer.addSubview(addButton)
}
#objc func createSecondContainer(){
print("something to complete")
}
}
My swift code uses func addBox to add and append image views to the uiview controller. All I want to do is when one of the image views are tapped is for func viewClicked to be activated. Right now nothing is happening and nothing is being written into the debug area.
import UIKit
class ViewController: UIViewController {
var ht = -90
var ww = 80
var hw = 80
var arrTextFields = [UIImageView]()
var b7 = UIButton()
override func viewDidLoad() {
[b7].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .systemOrange
}
b7.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 70, height: 40)
b7.addTarget(self, action: #selector(addBOx), for: .touchUpInside)
for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
}
#objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}
//func that adds imageview.
#objc func addBOx() {
let subview = UIImageView()
subview.isUserInteractionEnabled = true
arrTextFields.append(subview)
view.addSubview(subview)
subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: CGFloat(ww), height: 35)
subview.backgroundColor = .purple
ht += 50
arrTextFields.append(subview)
}
}
You need to enable user interation
for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
#objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}
my code below initializes 2 different imageviews pg and tim. I have create a seperate var for the UIPanGestureRecognizer to be used for each imageview and func to move the imageview around using UIPanGestureRecongizer. Right now I can not move the imageviews around. When I click on pg it disapers. I just want to develop a function that allows me to move each imageview around freely. All of my code is programmatically so you can just copy the code.
import UIKit
class ViewController: UIViewController {
var pg = UIImageView()
var pgGesture = UIPanGestureRecognizer()
var pgCon = [NSLayoutConstraint]()
var tim = UIImageView()
var timGesture = UIPanGestureRecognizer()
var timCon = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
[pg,tim].forEach({
$0.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview($0)
$0.backgroundColor = UIColor.systemPink
$0.isUserInteractionEnabled = true
})
pgGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.pgGestureMethod(_:)))
pg.addGestureRecognizer(pgGesture)
timGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.timGestureMethod(_:)))
tim.addGestureRecognizer(timGesture)
pgCon = [
pg.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :37.5),
pg.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 225),
pg.widthAnchor.constraint(equalToConstant: 75),
pg.heightAnchor.constraint(equalToConstant: 50),
]
NSLayoutConstraint.activate(pgCon)
timCon = [
tim.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :120),
tim.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 225),
tim.widthAnchor.constraint(equalToConstant: 75),
tim.heightAnchor.constraint(equalToConstant: 50),
]
NSLayoutConstraint.activate(timCon)
}
#objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
NSLayoutConstraint.deactivate(pgCon)
NSLayoutConstraint.deactivate(timCon)
self.view.bringSubviewToFront(pg)
let tranistioon = sender.translation(in: self.view)
pg.center = CGPoint(x: pg.center.x + tranistioon.x, y: pg.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
#objc func timGestureMethod(_ sender: UIPanGestureRecognizer){
NSLayoutConstraint.deactivate(timCon)
NSLayoutConstraint.deactivate(pgCon)
self.view.bringSubviewToFront(tim)
let tranistioon = sender.translation(in: self.view)
tim.center = CGPoint(x: tim.center.x + tranistioon.x, y: tim.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
}
Instead of constraints, try giving the frame to both imageViews, i.e.
override func viewDidLoad() {
super.viewDidLoad()
pg.frame = CGRect(x: 100, y: 100, width: 75, height: 50) //here....
tim.frame = CGRect(x: 200, y: 200, width: 75, height: 50) //here....
//rest of the code...
}
In the above code,
change the frame as per your requirement.
from viewDidLoad() remove the code for applying constraints.
I would like to use a simple function to update the text inside a UIlabel. I'm getting the error
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
I've looked into this problem and found this excellent post that suggested using optional binding/guard statements.
import UIKit
class ViewController: UIViewController {
var mainImageView: UIImageView!
var chooseButton: UIButton!
var nameLabel: UILabel!
override func loadView() {
view = UIView()
view.backgroundColor = .white
let btn = UIButton(type: .custom) as UIButton
btn.backgroundColor = .blue
btn.layer.borderColor = UIColor.darkGray.cgColor
btn.layer.borderWidth = 2
btn.setTitle("Pick a side", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
btn.layer.cornerRadius = btn.frame.size.height/2
self.view.addSubview(btn)
let nameLabel = UILabel()
nameLabel.text = "Here is your side"
nameLabel.textAlignment = .center
nameLabel.backgroundColor = .cyan
nameLabel.frame = CGRect(x: 100, y: 400, width: 200, height: 100)
self.view.addSubview(nameLabel)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#objc func clickMe(sender:UIButton!) {
print("Button Clicked")
self.nameLabel.text = "updated title"
}
}
The problem seems to be that you are adding the label manually in loadView but you are creating a local label object that you add to the view and not your class property so the class property nameLabel is always nil
Change
let nameLabel = UILabel()
to
self.nameLabel = UILabel()
I have this code that adds a rounded border around a UIImage using UIImageView and I've used UITapGestureRecognizer to let the user tap on the button:
var profilePicture = UIImageView()
func setupUserProfileButton() {
let defaultPicture = UIImage(named: "profilePictureSmall")
profilePicture = UIImageView(image: defaultPicture)
profilePicture.layer.cornerRadius = profilePicture.frame.width / 2
profilePicture.clipsToBounds = true
profilePicture.layer.borderColor = UIColor.black.cgColor
profilePicture.layer.borderWidth = 1
// Letting users click on the image
profilePicture.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(profilePictureTapped))
profilePicture.addGestureRecognizer(tapGesture)
}
How can I add this to the left side of a navigation bar? Is it possible? And I don't think the tap gesture is needed if I can add the ImageView to the navigation bar as a barButtonItem, so you can ignore that. I kinda found some similar questions but they were in objective C and none of what I tried worked.
Here is what I came up with based on an answer:
import UIKit
import Firebase
class CreateStoryPage: BaseAndExtensions {
let userProfileButton = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
// Call all the elements
setupUserProfileButton()
}
// MARK:- Setups
// Setup the user profile button
func setupUserProfileButton() {
userProfileButton.setImage(#imageLiteral(resourceName: "profilePictureSmall.png"), for: .normal)
userProfileButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
userProfileButton.addTarget(self, action: #selector(profilePictureTapped), for: .touchUpInside)
let userProfileView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
userProfileView.layer.cornerRadius = 14
userProfileView.backgroundColor = .red
userProfileView.addSubview(userProfileButton)
let leftNavBarItem = UIBarButtonItem(customView: userProfileView)
self.navigationItem.setLeftBarButton(leftNavBarItem, animated: true)
}
// if user taps on profile picture
#objc func profilePictureTapped() {
let userProfilePage = UserProfilePage()
present(userProfilePage, animated: true, completion: nil)
}
}
Try this;
private func setupRightItem() {
let userProfileButton = UIButton(type: .custom)
userProfileButton.imageView?.contentMode = .scaleAspectFill
userProfileButton.clipsToBounds = true
userProfileButton.addTarget(self, action: #selector(profilePictureTapped), for: .touchUpInside)
userProfileButton.setImage(#imageLiteral(resourceName: "profilePictureSmall.png"), for: .normal)
userProfileButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: userProfileButton)
userProfileButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
userProfileButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
#objc private func goProfile() {
/// -> Action
}
let navBtn = UIButton(type: .custom)
navBtn.setImage("yourImage", for: .normal)
navBtn.frame = CGRect(x: 0, y: 0, width: 28, height: 28)
navBtn.addTarget(self, action: #selector(self.openProfile(_:)), for: .touchUpInside)
let view = UIView(frame: CGRect(x: 0, y: 0, width: 28, height: 28))
view.cornerRadius = 14
view.backgroundColor = Global.colorBlue
view.addSubview(navBtn)
let leftNavBarItem = UIBarButtonItem(customView: view)
self.navigationItem.setLeftBarButton(leftNavBarItem, animated: true)
#objc
func openProfile(_ sender: UIButton) {
}