What is the difference between UIbutton.setImage and changing UIbutton.imageView?
buttonA.imageView?.image = UIImage(named: "name")
buttonA.setImage(UIImage(named: "name"), for: .normal)
When I try to use setImage and then try to get it's position using frame.origin.x, the position returned are not what I expected and so I used .imageView?.image approach. But when I use that, I observed that clicking on the button changes the image for a brief time before continuing.
the function offers you the ability to set different icons for various states
setImage(imageNormal, for: .normal) //normal state
setImage(disabledImage, for: .disabled) //disable UI representation
UIButton.imageView according to documentation read-only property https://developer.apple.com/documentation/uikit/uibutton/1624033-imageview
For some clarification...
If you set the .image property directly:
buttonA.imageView?.image = UIImage(named: "name")
You have not informed the button class that it has a new image property.
The same thing applies to setting the title:
buttonA.titleLabel?.text = "My Title"
That will change the text of the title label, but only until the next UI update... at which point UIKit will use the value assigned via:
buttonA.setTitle("Button A", for: .normal)
That's why it's important to use both .setImage(...) and .setTitle(...) instead of setting the property itself.
Related
let newLabel = UILbael()
let button = UIButton()
button.setValue(newLabel, forKeyPath: "titleLabel")
crash info
setValue:forUndefinedKey:]: this class is not key valuecoding-compliant for the key titleLabel
how do it if use kvc ?
You should use setTitle method to set button title for states.
button.setTitle("Your button title here", for: .normal)
setValue(_:forKeyPath:) is a method from NSObject class which UIButton is a subclass of. It is not recommended to use KVO. Read this thread for more information.
KVC is only supported for NSObjects, and Apple seems to be phasing it out in Swift. I don't recommend using KVC for new development.
You also shouldn't use the button's titleLabel to set the button's title. To quote the Apple docs on UIButton:
To set the actual text of the label, use setTitle(_:for:)
(button.titleLabel.text does not let you set the text).
If you have two buttons, firstButton and secondButton, and you're trying to copy the title from the first to the second, your code might look like this:
let title = firstButton.title(forState: .normal)
secondButton.setTitle(title, for: .normal)
I think u have not confirmed your outlet in your ViewController that's a reason when use button and set title there are not any references of a button in ViewController. it's like the use of any object without any initialize. So make sure and check button outlet. Please see code so we make sure what is actual problem.
so I'm very new to swift. I currently have 16 buttons all set to individual outlets box1,box2,box3 etc.
Each box I have set a tag and what I am trying to do is set the image of a particular box based off another integer variable to determine which box I'm changing.
So say I do a calculation and index = 4.
Is there a way I can then set box(index).setImage?
I understand this probably isn't the best way to do it or even possible, maybe I can set each button to an array of objects instead? Any tips would be great.
If you want to set the image of button through some tag then you don't need any outlets for the buttons.
You can change your button image by finding the button through viewWithTag() property.
Here is the code
var button = self.view.viewWithTag(Your_Calculated_Index) as! UIButton
button.setImage(Your_Image, for: .normal)
You can try this. You need to create an array for the button.
#IBOutlet var allbtns: [UIButton]!
for buttons in allbtns{
if buttons.tag == 4{
print("Button 4 ");
buttons.setImage(UIImage(named: "imagname"), for: UIControlState.normal)
}else{
print("Other buttons except 4 ");
}
}
I am setting UIAlertAction label attributedText in order to set custom Font in UIAlertController.It works but when i tap on the UIAlertAction it changes its font to default for some time and then disappears. Here is the code
let lb = (action.value(forKey: "__representer") as AnyObject)
let label = lb.value(forKey: "label") as? UILabel
label?.attributedText = myMutableString
I think best idea would be to create your own custom alert controller instead of accessing private properties to set your values. Not sure if Apple would accept it or not.
I don't know the solution for your problem but I know the problem which is
Problem: When you press UIAlertAction's button it changes its state. It behaves just like the states of UIButton. So if you know which property you should set for its highlighted state then you can set that to solve this issue.
I have been looking and trying to solve an issue I have with a UIWebView for iOS.
I have a very small app which just loads my website the source code lives at https://github.com/pjuu/iotter.
On the site when a user clicks on a posted image it load the image URL in to the web view. This leaves them stranded and unable to get back to other parts of the site.
What I want to do is display an (x) button in the top right hand corner (no matter what screen rotation is in use) and have perform the back operation in the browser.
I know this question isn't a code issue as I'm fine to sort of the Swift code part of it. I just could not for the life of me work out how to add the button programmatically and have it display over the webview.
The only tutorials I could find involved creating a tool bar to perform these type of actions which I think would take up to much space when looking at an image.
The question is very simple:
Is this possible?
If so how would I go about creating the button?
I am going to check the request.path parameter with regex to only show it if it matches an image URL.
Apologies if this isn't fitting enough for SO. I am happy to move the question or post on another site.
Thank you for any help in advance. I am not a mobile developer so using XCode and the storyboard stuff is a world away from vim for me.
REFERENCE:
1) CGRectMake: https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGGeometry/#//apple_ref/c/func/CGRectMake
2) UIWebViewDelegate:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/#//apple_ref/occ/intfm/UIWebViewDelegate/webView:shouldStartLoadWithRequest:navigationType:
SOLUTION:
1) Create the "X" UIButton:
// Define the UIButton
let button = UIButton(type: UIButtonType.System) as UIButton
let image = UIImage(named: "name") as UIImage?
button.frame = CGRectMake(self.view.frame.width - 60, 30, 35, 35)
button.setTitle("Test Button", forState: UIControlState.Normal)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
//Hide the UIButton
button.hidden = true
2) Detect when an imageUrl is opened and make the "X" UIButton appear:
// This function is triggered every time a request is made:
optional func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let string = request.URL
if string.rangeOfString(".png") || string.rangeOfString(".jpg")|| string.rangeOfString(".jpeg"){
// code to make cross appear
// for example:
self.button.hidden = false
}
}
3) Finally, you will need to create the method that closes the page when the "X" UIButton is tapped:
func btnPressed(sender: UIButton!) {
if(webview.canGoBack) {
//Go back in webview history
webview.goBack()
} else {
//Pop view controller to preview view controller
self.navigationController?.popViewControllerAnimated(true)
}
}
N.B.:
In the lines:
let image = UIImage(named: "cross.png") as UIImage?
button.setImage(image, forState: .Normal)
We are setting the UIButton to be the image of a cross.
You need to add a cross image to your XCode project and set the "cross.png" String to the exact name of your image: "nameOfImage.fileType".
Simple one line solution.
Create a desired "close" button in storyboard, or programmatically.
Then, just send your WebView to the back of all current views displayed in your view controller:
view.sendSubviewToBack(yourWebView)
Now, all views (including any buttons you create) will be displayed on top if it. Just be sure to add this line after all of your desired views are created.
In a reset button where I want to reset my game when I try to set my image to nil Xcode displays this error:
Could not cast value of type 'UIView' (0x106c26e88) to 'UIButton'
(0x106c2cf68).
This is my code:
var button : UIButton
for var i = 0; i < 9; i++ {
button = self.view.viewWithTag(i) as! UIButton
button.setImage(nil, forState: .Normal)
}
The best way to do this is set the contents to the path of the file as empty or invalid
let image = UIImage(contentsOfFile: "")
You can insert nil image to your button as
let btnCheckMarkImage = UIImage(CGImage: nil)
checkBoxbtn.setImage(btnCheckMarkImage, forState: UIControlState.Normal)
For anyone who finds this issue and is trying to solve the problem from the title,
button.setImage(nil, for: .normal)
should produce the desired result.
(Added my answer to this post as it was the first result in Google.)
By the error, the problem seems to be that one of the tagged views you are trying to cast as UIButton isn't really an UIButton class object
I found my view tag = 0 and this is what make the app crash