I have been doing it great with the answer in this question:
Strange #IBAction conflict or bug? (Swift)
But since I put iAds, the random position stop working that well, now the button is showed sometimes at his real place in Main.storyboard and sometimes at a random place inside the screen, this is only when iAd is showing
here is the code:
var newButtonX: CGFloat?
var newButtonY: CGFloat?
#IBAction func buttonPressed(sender: AnyObject) {
let buttonWidth = button.frame.width
let buttonHeight = button.frame.height
// Find the width and height of the enclosing view
let viewWidth = button.superview!.bounds.width
let viewHeight = button.superview!.bounds.height
// Compute width and height of the area to contain the button's center
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
// Generate a random x and y offset
let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
// Offset the button's center by the random offsets.
newButtonX = xoffset + buttonWidth / 2
newButtonY = yoffset + buttonHeight / 2
circle.center.x = newButtonX!
circle.center.y = newButtonY!
}
override func viewDidLayoutSubviews() {
if let buttonX = newButtonX {
button.center.x = buttonX
}
if let buttonY = newButtonY {
button.center.y = buttonY
}
}
Just solve it, I use the iAd bannerview on the Main.storyboard and now it works fine
Related
i am dropping pin image on imageview with coordinates so pin set correctly but there is minor position difference in various devices i am sharing my code below
func convertTapToImg(_ point: CGPoint) -> CGPoint? {
let xRatio = imgView.frame.width / (img?.size.width)!
let yRatio = imgView.frame.height / (img?.size.height)!
let ratio = min(xRatio, yRatio)
let imgWidth = (img?.size.width)! * ratio
let imgHeight = (img?.size.height)! * ratio
var tap = point
var borderWidth: CGFloat = 0
var borderHeight: CGFloat = 0
// detect border
if ratio == yRatio {
// border is left and right
borderWidth = (imgView.frame.size.width - imgWidth) / 2
if point.x < borderWidth || point.x > borderWidth + imgWidth {
return nil
}
tap.x -= borderWidth
} else {
// border is top and bottom
borderHeight = (imgView.frame.size.height - imgHeight) / 2
if point.y < borderHeight || point.y > borderHeight + imgHeight {
return nil
}
tap.y -= borderHeight
}
let xScale = tap.x / (imgView.frame.width - 2 * borderWidth)
let yScale = tap.y / (imgView.frame.height - 2 * borderHeight)
let pixelX = (img?.size.width)! * xScale
let pixelY = (img?.size.height)! * yScale
return CGPoint(x: pixelX, y: pixelY)
}
then with tap-gesture i have fetched one x y coordinates as below
#objc func tapGesture(_ gesture: UITapGestureRecognizer) {
let point = gesture.location(in: imgView)
let imgPoint = convertTapToImg(point)
print("tap: \(point) -> img \(imgPoint)")
}
then after i am set up pin like below with coordinates
var xCo = 83.0
var yCo = 404.0
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "ic_Pin")
imageView.frame = CGRect(x: xCo - 20, y: yCo - 20, width: 22, height: 22)
imgView.addSubview(imageView)
now i am sharing screen shot of various devices output there is just minor difference with pin position
This is iPhone 5s Screen Shot
This is iPhone 6 Screen Shot
This is iPhone XR Screen Shot
please check screen shot and please help that how to set pin position same on all devices
I have one UIScrollView (IBOutlet) with success constraint inside a storyboard. then I programmatically create UIButton and put them as a subview to UIScrollView. how do I programmatically set these UIButton constraints so their height and size would tally with their super view?
class ViewController: UIViewController {
#IBOutlet weak var aScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var xCoord: CGFloat = 5
let yCoord: CGFloat = 5
let buttonWidth:CGFloat = 100
let buttonHeight: CGFloat = 100
let gapBetweenButtons: CGFloat = 10
var itemCount = 0
// MARK: - filter buttons
for i in 0..<6 {
itemCount = i
let aButton = UIButton(type: .custom)
aButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
aButton.backgroundColor = UIColor.blue
aButton.layer.cornerRadius = aButton.frame.size.width / 2
aButton.clipsToBounds = true
xCoord += buttonWidth + gapBetweenButtons
aScrollView.addSubview(aButton)
}
}
Try this --
This is just an idea about how to add constraint programmatically.
For more understanding you can go through below link - https://developer.apple.com/reference/appkit/nslayoutanchor
let myButton = UIButton()
self.aScrollView.addSubview(myButton)
self.view.translatesAutoresizingMaskIntoConstraints = false
let margins = self.view.layoutMarginsGuide
myButton.leadingAnchor.constraint(equalTo: forView. aScrollView.leadingAnchor, constant: 5).active = true
myButton.topAnchor.constraint(equalTo: forView. aScrollView.topAnchor, constant: 5).active = true
myButton.heightAnchor.constraintEqualToConstant(100.0).active = true
myButton.widthAnchor.constraintEqualToConstant(100.0).active = true
Change your code to:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var xCoord: CGFloat = 5
let yCoord: CGFloat = 5
let gapBetweenButtons: CGFloat = 10
let buttonCount = 6
let buttonWidth = (aScrollView.frame.width - CGFloat(buttonCount - 1) * gapBetweenButtons - xCoord - xCoord) / CGFloat(buttonCount) // - (2 * xCoord) = - (margin left + margin right).
let buttonHeight = buttonWidth
var itemCount = 0
// MARK: - filter buttons
for i in 0..<buttonCount {
itemCount = i
let aButton = UIButton(type: .custom)
aButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
aButton.backgroundColor = UIColor.blue
aButton.layer.cornerRadius = aButton.frame.size.width / 2
aButton.clipsToBounds = true
xCoord += buttonWidth + gapBetweenButtons
aScrollView.addSubview(aButton)
}
}
This is how to do it. I made a video tutorial for you add unbutton programmatically to scrollview in iOS, swift. please refer the link.
add a scrollview (add constraints -> top, bottom, left, right).
then add a view to your scroll view (add constraints -> top, bottom, left, right, width, height and set width and height as you need. explain in the video)
add those two views as subviews.
then add the button and its constraints programmatically.
follow the video tutorial. add UIButton(outlet) to scrollview programmatically
I'm trying to move a label to a random location which I have been able to do so using this code.
let buttonWidth = self.samea.frame.width
let buttonHeight = self.samea.frame.height
// Find the width and height of the enclosing view
let viewWidth = self.samea.superview!.bounds.width
let viewHeight = self.samea.superview!.bounds.height
// Compute width and height of the area to contain the button's center
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
// Generate a random x and y offset
let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
// Offset the button's center by the random offsets.
self.newButtonX = xoffset + buttonWidth/2
self.newButtonY = yoffset + buttonHeight/2
self.samea.center.x = self.newButtonX!
self.samea.center.y = self.newButtonY!
The problem is, I have some buttons and labels on the storyboard and I do not want the button to spawn on top of those. Not sure how to do that. Any help is appreciated !
You can create an array property of all the UIButton and UILabel outlets that you have, populate it in your viewDidLoad(_:) method. Then when you're generating your random values, you can put them in a while loop and cycle through the values.
Something like this.
let buttonsAndLabels = [UIView]()
var xoffset: CGFloat
var yoffset: CGFloat
var isOccupied = true
while isOccupied {
xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
let frame = CGRect(x: xoffset, y: yoffset, width: buttonWidth, height: buttonHeight)
isOccupied = false
for view in buttonsAndLabels {
if view.frame.intersects(frame) {
isOccupied = true
}
}
}
I have this code for my UIButton. What should I change in my CGRectMake to set my UIButton in the center of the screen for all screen sizes?
let loginBtn = UIButton(frame: CGRectMake(60, 360, 240, 40))
loginBtn.layer.borderColor = UIColor.whiteColor().CGColor
loginBtn.layer.borderWidth = 2
loginBtn.titleLabel!.font = UIFont.systemFontOfSize(24)
loginBtn.tintColor = UIColor.whiteColor()
loginBtn.setTitle("Login", forState: UIControlState.Normal)
self.view.addSubview(loginBtn)
For your place uibutton center of your view , update your cgrectmake as bleow..
CGRectMake((self.view.frame.size.width - 240) / 2, (self.view.frame.size.height - 40) / 2,240,40)
or
You can add one line after your code
loginBtn.center = self.view.center
For SignUp Button :
signup.frame = loginBtn.bounds
signup.center = CGPointMake(loginBtn.center.x, loginBtn.center.y + loginBtn.frame.size.height + 10)
Set your UIButton's center to the center of the view it is in.
loginBtn.center = view.center
You need add the following line prior to self.view.addSubview(loginBtn).
loginBtn.center = self.view.center
This will center the button across the whole screen, not just the view it's in:
let verticalCenter: CGFloat = UIScreen.mainScreen().bounds.size.height / 2.0
let horizontalCenter: CGFloat = UIScreen.mainScreen().bounds.size.width / 2.0
loginBtn.center = CGPoint(x: horizontalCenter, y: verticalCenter)
Edit:
As #LeoDabus pointed out, this can be compacted by using the midX and midY properties on CGRect:
let verticalCenter: CGFloat = UIScreen.mainScreen().bounds.midY
let horizontalCenter: CGFloat = UIScreen.mainScreen().bounds.midX
For Swift 4
#IBOutlet weak var btStart: UIButton!
on the middle of any screen (any device)
btStart.center = self.view.center
OR
btStart.center.x = self.view.center.x
btStart.center.y = self.view.center.y
on the center by x and 25 percent from top
btStart.center.x = self.view.center.x
btStart.center.y = self.view.center.y / 2
I found this to be the best solution for me..
Swift 4
myButton.center.x = self.view.frame.midX
myButton.center.y = self.view.frame.midY
I found if I need to center things quite often, I usually use a generic solution.
extension UIViewController {
func centerComponent(_ component: AnyObject) {
let customView = component as! UIView
customView.center.x = self.view.frame.midX
customView.center.y = self.view.frame.midY
}
}
then you can call it from any UIViewcontroller inside a function like so:
centerComponent(myButton)
I'm creating a very simple app for iPhone.
Just don't know how to make the button (image) move to random position (but on the screen) when it's touched, in Swift.
I'm using Xcode 6.
Use this for the #IBAction of your button:
#IBAction func moveButton(button: UIButton) {
// Find the button's width and height
let buttonWidth = button.frame.width
let buttonHeight = button.frame.height
// Find the width and height of the enclosing view
let viewWidth = button.superview!.bounds.width
let viewHeight = button.superview!.bounds.height
// Compute width and height of the area to contain the button's center
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
// Generate a random x and y offset
let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
// Offset the button's center by the random offsets.
button.center.x = xoffset + buttonWidth / 2
button.center.y = yoffset + buttonHeight / 2
}
Warning: If you have AutoLayout enabled, your button could snap back to its original location when the subviews are laid out. See the solution to this problem here.